kotlin:flow: 用try/catch捕捉下游的异常
一,代码:
//处理按钮点击事件
binding.button1.setOnClickListener {
runBlocking {
//用 try catch 处理下游异常
flowOf(4, 5, 6)
.onCompletion { println("onCompletion: $it") }
.collect {
try {
println("collect: $it")
throw IllegalStateException()
} catch (e: Exception) {
println("Catch $e")
}
}
}
}
对于发生在下游的异常, 不能用 catch 操作符处理。
最简单的办法,其实是使用 try-catch,把 collect{} 当中可能出现问题的代码包裹起来。
总结:
所以,针对 Flow 当中的异常处理,我们主要有两种手段:
一个是 catch 操作符,它主要用于上游异常的捕获;
一个是 try-catch 这种传统的方式,它主要应用于下游异常的捕获。