我可以通过以下操作轻松地将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
中的值(成功后返回值)。
什么是最好的方法?
答案 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)
}