如何链接协程流?

时间:2020-03-02 09:16:56

标签: kotlin-coroutines kotlin-flow

我可以通过以下操作轻松地将StringSet[Async] coroutine链接起来:

Flow

但是,如果我想分别重试val someFlow = flow { //Some logic that my succeed or throw error } val anotherFlow = flow { // Another logic that my succeed or throe error } val resultingFlow = someFlow.flatmapLatest(anotherFlow) someFlow会怎样,如果anotherFlow已经成功返回值但someFlow失败了,我想重试anotherFlow,使用anotherFlow中的值(成功后返回值)。

什么是最好的方法?

2 个答案:

答案 0 :(得分:1)

您可以像这样在retryWhen上使用anotherFlow运算符:

val someFlow = flow { 
    //Some logic that my succeed or throw error 
}

val anotherFlow = flow { 
    // Another logic that my succeed or throe error 
}
.retryWhen { cause, attempt ->
    if (cause is IOException) {    // retry on IOException
        emit(“Some value”)         // emit anything you want before retry
        delay(1000)                // delay for one second before retry
        true
    } else {                       // do not retry otherwise
        false
    }
}

val resultingFlow = someFlow.flatmapLatest(anotherFlow)

请小心,因为您可能会永远重试。使用attempt参数检查重试次数。

这是retryWhen操作员的官方文档:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/retry-when.html

答案 1 :(得分:0)

您是否考虑过使用zip
我尚未进行测试或进行任何测试,但这可能值得一试。

val someFlow = flow {}
val anotherFlow = flow {}
someFlow.zip(anotherFlow) { some, another ->
    if(another is Resource.Error)
        repository.fetchAnother(some)
    else
        some
}.collect {
    Log.d(TAG, it)
}