34

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Jahid Hasan
  • 439
  • 1
  • 4
  • 4
  • 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 Answers2

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
2

i think this article made it simple with example.

The tradeoff between collect { ... } and collectLatest { ... } is simple. when you need to process all the values you receive, you should use collect, and when you want only the latest value to be processed, use collectLatest.

Sep
  • 147
  • 8