kotlin协程flow retry retryWhen(2)
一、retry
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) {
runBlocking {
(1..5).asFlow().onEach {
if (it == 3) {
println("-")
throw RuntimeException("error $it")
}
}.retry(2) {
if (it is RuntimeException) {
println("--")
return@retry true
}
false
}.onEach {
println("onEach $it")
}.catch {
println("catch $it")
}.onCompletion {
println("onCompletion")
}.collect {
println("collect $it")
}
}
}
onEach 1
collect 1
onEach 2
collect 2
-
--
onEach 1
collect 1
onEach 2
collect 2
-
--
onEach 1
collect 1
onEach 2
collect 2
-
catch java.lang.RuntimeException: error 3
onCompletion
二、retryWhen
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) {
runBlocking {
(1..5).asFlow().onEach {
if (it == 3) {
println("-")
throw RuntimeException("error $it")
}
}.retryWhen { cause, attempt ->
if (cause is RuntimeException) {
println("--")
}
attempt < 2
}.onEach {
println("onEach $it")
}.catch {
println("catch $it")
}.onCompletion {
println("onCompletion")
}.collect {
println("collect $it")
}
}
}
onEach 1
collect 1
onEach 2
collect 2
-
--
onEach 1
collect 1
onEach 2
collect 2
-
--
onEach 1
collect 1
onEach 2
collect 2
-
--
catch java.lang.RuntimeException: error 3
onCompletion
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) {
runBlocking {
(1..5).asFlow().onEach {
println("-----")
var p: Int = (Math.random() * 10).toInt() % 3
println("it=$it p=$p")
if (it == p) {
println("error=$p")
throw RuntimeException("error-$it")
} else {
println("onEach $it")
}
}.retryWhen { cause, attempt ->
if (cause is RuntimeException) {
println("cause RuntimeException")
}
attempt < 2
}.catch {
println("catch $it")
}.onCompletion {
println("onCompletion")
}.collect {
println("collect $it")
}
}
}
随机跑一次:
-----
it=1 p=0
onEach 1
collect 1
-----
it=2 p=1
onEach 2
collect 2
-----
it=3 p=0
onEach 3
collect 3
-----
it=4 p=2
onEach 4
collect 4
-----
it=5 p=1
onEach 5
collect 5
onCompletion
再跑:
-----
it=1 p=0
onEach 1
collect 1
-----
it=2 p=2
error=2
cause RuntimeException
-----
it=1 p=0
onEach 1
collect 1
-----
it=2 p=2
error=2
cause RuntimeException
-----
it=1 p=2
onEach 1
collect 1
-----
it=2 p=2
error=2
cause RuntimeException
catch java.lang.RuntimeException: error-2
onCompletion
又跑:
-----
it=1 p=0
onEach 1
collect 1
-----
it=2 p=2
error=2
cause RuntimeException
-----
it=1 p=2
onEach 1
collect 1
-----
it=2 p=1
onEach 2
collect 2
-----
it=3 p=2
onEach 3
collect 3
-----
it=4 p=2
onEach 4
collect 4
-----
it=5 p=2
onEach 5
collect 5
onCompletion
https://zhangphil.blog.csdn.net/article/details/130084723https://zhangphil.blog.csdn.net/article/details/130084723