collectLatest

suspend fun <T> Flow<T>.collectLatest(action: suspend (value: T) -> Unit)(source)

Terminal flow operator that collects the given flow with a provided action. The crucial difference from collect is that when the original flow emits a new value then the action block for the previous value is cancelled.

It can be demonstrated by the following example:

flow {
emit(1)
delay(50)
emit(2)
}.collectLatest { value ->
println("Collecting $value")
delay(100) // Emulate work
println("$value collected")
}

prints "Collecting 1, Collecting 2, 2 collected"