mapLatest

@ExperimentalCoroutinesApi 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 1” and “Started computing 2”, but the resulting flow will contain only “Computed 2” value.

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