The kotlin coroutine flow task ends unexpectedly without emitting data retryWhen onEmpty(5)
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
fun main(args: Array<String>) {
val MSG = "fly_error"
runBlocking {
load().onStart {
println("---")
println("onStart")
}.onEach {
if (it == null) {
throw Exception(MSG)
} else {
println("获取数据 $it")
}
}.retryWhen { cause, attempt ->
println("${cause.message}")
println("retry ${attempt}")
delay(100) //延时重试
attempt < 3 //重试3次
}.catch {
it.printStackTrace() //如果重试3次仍失败,此次将抛出异常打印错误栈
}.onCompletion {
println("onCompletion")
}.onEmpty {
// flow完成但没有发射任何元素。
// 可用onEmpty发射一些默认的空态值。
println("onEmpty")
emit("empty")
}.collect {
println("collect $it")
}
}
}
fun load() = flow {
var time = 1000L
withTimeoutOrNull(time) {
//生成一个概率布尔,模拟加载概率性成功/失败
var b = Boolean.let {
var p: Int = (Math.random() * 100).toInt() % 2
when (p) {
0 -> true
1 -> false
else -> false
}
}
var s: String? = null
if (b) {
println("加载成功")
s = "fly"
} else {
println("加载失败")
}
delay(time + 1) //模拟超时
emit(s)
}
}
---
onStart
load failure
onCompletion
onEmpty
collect empty
The kotlin coroutine flow retry function returns to retry after failure (4) _zhangphil's blog-CSDN blog 1. flow, emit, onCompletion, collect. kotlin coroutine flow retryWhen retry when the function function fails to load (3)_zhangphil's blog-CSDN blog. The kotlin coroutine flow retryWhen retry when the function function fails to load (3) Loading fails once, and retrying succeeds once. kotlin coroutine flow retry retryWhen (2)_zhangphil's blog - CSDN blog. kotlin coroutine flow retry retryWhen (2) Second, retryWhen. Failed to load the first time, retries succeeded twice. https://blog.csdn.net/zhangphil/article/details/130093111 kotlin coroutine flow retryWhen when the function function fails to load, retry (3)_zhangphil's blog-CSDN blog kotlin coroutine flow retryWhen when the function function fails to load Retry (3) failed to load once, retry 1 successfully. https://blog.csdn.net/zhangphil/article/details/130092299