When to use collect and collectLatest operator to collect kotlin flow?

Collect will collect every value , and CollectLatest will stop current work to collect latest value,

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.

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

prints "Collecting 1, 1 collected, Collecting 2, 2 collected"

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"

So , if every update is important like state, view, preferences updates, etc , collect should be used .
And if some updates can be overridden with no loss , like database updates , collectLatest should be used.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)