简体   繁体   English

何时使用 collect 和 collectLatest 算子收集 kotlin 流量?

[英]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.我知道区别,但与我的实现无关。

Collect will collect every value, and CollectLatest will stop current work to collect latest value, Collect 将收集每个值,CollectLatest 将停止当前工作以收集最新值,

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.因此,如果每个更新都很重要,例如 state、视图、首选项更新等,则应使用 collect。 And if some updates can be overridden with no loss, like database updates, collectLatest should be used.如果可以无损失地覆盖某些更新,例如数据库更新,则应使用 collectLatest。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM