mapLatest

fun <T, R> Flow<T>.mapLatest(transform: suspend (value: T) -> R): Flow<R>(source)

Returns a flow that emits elements from the original flow transformed by transform function. When the original flow emits a new value, computation of the transform block for previous value is cancelled.

For example, the following flow:

flow {
emit("a")
delay(100)
emit("b")
}.mapLatest { value ->
println("Started computing $value")
delay(200)
"Computed $value"
}

will print "Started computing a" and "Started computing b", but the resulting flow will contain only "Computed b" value.

This operator is buffered by default and size of its output buffer can be changed by applying subsequent buffer operator.