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

Jah*_*san 42 kotlin kotlin-coroutines kotlin-flow

我想知道他们俩的实际场景。我知道其中的区别,但无法与我的实现联系起来。

Ans*_*hul 74

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")
}
Run Code Online (Sandbox Code Playgroud)

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")
}
Run Code Online (Sandbox Code Playgroud)

prints "Collecting 1, Collecting 2, 2 collected"

因此,如果每个更新都很重要,例如状态、视图、首选项更新等,则应使用收集。如果某些更新可以无损失地覆盖,例如数据库更新,则应使用collectLatest。