1

我可以通过以下方式轻松链接coroutine Flows:

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)

但是如果我想单独重试someFlowanotherFlow如果someFlow已经成功返回一个值但anotherFlow失败了,我想anotherFlow通过使用来自someFlow(成功时返回的值)的值重试。

最好的方法是什么?

4

2 回答 2

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

于 2020-03-02T11:15:37.633 回答
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)
}
于 2020-10-07T01:43:28.837 回答