I want to know a practical scenario of both of them. I know the difference but couldn't relate to my implementation.
Asked
Active
Viewed 1.3k times
34
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 13 '22 at 11:59
2 Answers
65
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.

Anshul
- 1,495
- 9
- 17
-
What is the `delay` represents here? Is it a network call or a database access? – Bitwise DEVS Aug 14 '22 at 06:21
-
@BitwiseDEVS, can be, it represents something which takes some time to compute/access – Anshul Aug 14 '22 at 23:10
-
what about `.conflate()` + collect{}, does it do the same or different? – lannyf Jul 26 '23 at 19:13