kotlin:flow: 用catch捕捉位于它上游的异常
一,代码:
//处理按钮点击事件: 异常位于catch上游
binding.button1.setOnClickListener {
runBlocking {
val flow = flow {
emit(1)
emit(2)
throw IllegalStateException()
emit(3)
}
flow.map { it * 2 }
.catch { println("catch: $it") } // 注意这里
.collect {
println("collect:"+it)
}
}
}
//处理按钮点击事件: 异常位于catch下游
binding.button2.setOnClickListener {
runBlocking {
val flow = flow {
emit(1)
emit(2)
emit(3)
}
flow.map { it * 2 }
.catch { println("catch: $it") }
.filter { it / 0 > 1} // 故意制造异常
.collect {
println("collect:"+it)
}
}
}
//处理按钮点击事件: 异常位于catch上游
binding.button3.setOnClickListener {
runBlocking {
val flow = flow {
emit(1)
emit(2)
emit(3)
}
flow.map { it * 2 }
.filter { it / 0 > 1} // 故意制造异常
.catch { println("catch: $it") }
.collect {
println("collect:"+it)
}
}
}
说明:
对于发生在上游、中间操作这两个阶段的异常,我们可以直接使用 catch 这个操作符来进行捕获和进一步处理
catch 的作用域,仅限于 catch 的上游。
换句话说,发生在 catch 上游的异常,才会被捕获,发生在 catch 下游的异常,则不会被捕获
catch 对于发生在它下游的异常是无能为力的
二,运行结果:
第一个按钮点击后输出:
第二个按钮点击后:因为捕捉不到异常,发生崩溃
第三个按钮点击后:捕捉到了异常