kotlin协程flow retry功能函数返回失败后重试(4)
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) {
var count = 0 //重试计数
runBlocking {
load().onEach {
if (it == null) {
throw NullPointerException()
} else {
println("获取数据 $it")
}
}.retry(3) { //重试3次
println("retry ${count++}")
delay(1000) //延时重试
if (it is NullPointerException)
//为空时重试
true
else
false
}.catch {
it.printStackTrace() //如果重试3次仍失败,此次将抛出异常打印错误栈
}.onCompletion { println("onCompletion") }
.collect { println("collect $it") }
}
}
fun load() = flow {
//生成一个概率布尔,模拟加载概率性成功与失败
var b = Boolean.let {
var p: Int = (Math.random() * 10).toInt() % 2
when (p) {
0 -> true
1 -> false
else -> false
}
}
var s: String? = null
if (b) {
println("加载成功")
s = "fly"
} else {
println("加载失败")
}
emit(s)
}
初次加载失败,重试一次成功:
加载失败
retry 0
加载成功
获取数据 fly
collect fly
onCompletion
初次加载即成功:
加载成功
获取数据 fly
collect fly
onCompletion
初次加载失败,重试两次成功
加载失败
retry 0
加载失败
retry 1
加载成功
获取数据 fly
collect fly
onCompletion
kotlin协程flow retryWhen当功能函数加载失败后重试(3)_zhangphil的博客-CSDN博客kotlin协程flow retryWhen当功能函数加载失败后重试(3)加载一次失败,重试1次成功。https://blog.csdn.net/zhangphil/article/details/130092299
kotlin协程flow retry retryWhen(2)_zhangphil的博客-CSDN博客kotlin协程flow retry retryWhen(2)二、retryWhen。https://blog.csdn.net/zhangphil/article/details/130086523
kotlin协程flow filter map flowOn zip combine(1)_zhangphil的博客-CSDN博客一、flow ,emit,onCompletion,collect。四、map,重组改写数据。八、conflate 合并。九、debounce去重。二、函数作为flow。https://blog.csdn.net/zhangphil/article/details/130084723