何时使用collect和collectLatest运算符来收集kotlin流量



我想了解两者的实际场景。我知道其中的区别,但无法理解我的实现。

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"

因此,如果每个更新都很重要,比如状态、视图、首选项更新等,那么应该使用collect。如果某些更新可以被覆盖而不会丢失,比如数据库更新,那么应该使用collectLatest。

我认为这篇文章通过示例使它变得简单。

collect{…}collectLatest{…}之间的折衷很简单。当您需要处理收到的所有值时,应使用collect;当您只想处理最新值时,请使用collectLatest

最新更新