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

I want to know a practical scenario of both of them. I know the difference but couldn't relate to my implementation.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anshul