说我需要用Flowable包装BroadcastReceiver
:
Flowable
.create<Boolean>({ emitter ->
val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
throw RuntimeException("Test exception")
}
}
application.registerReceiver(broadcastReceiver, IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION))
}, BackpressureStrategy.MISSING)
.onErrorReturn { false }
然后,我需要在一个地方捕获Flowable内部引发的所有异常。
我认为onErrorReturn
应该能够在broadcastReceiver中捕获该throw RuntimeException("Test exception")
,但是它不能捕获该异常并导致应用崩溃。
当然,我可以使用try/catch
将所有内容包装在BroadcastReceiver中。但是实际上,我在那里有很多源代码,因此添加try/catch
会使源代码非常混乱。
有没有办法在一个地方捕获Flowable内部任何一行中抛出的所有异常?
答案 0 :(得分:3)
如果Flowable#create()
遵循Flowable
的合同,如果您有错误并希望通过流进行传递,则需要捕获它并调用emitter.onError()
。如果这样做,Flowable.onErrorReturn()
将按预期开始工作。
要正确注册/注销BroadcastReceiver
并处理异常,您可以使用该方法
Flowable
.create<Boolean>({ emitter ->
val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
try {
throw RuntimeException("Test exception")
} catch(e: Throwable) {
emitter.tryOnError(e)
}
}
}
try {
application.registerReceiver(broadcastReceiver, IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION))
emitter.setCancellable {
application.unregisterReceiver(broadcastReceiver)
}
} catch (e: Throwable) {
emitter.tryOnError(e)
}
}, BackpressureStrategy.MISSING)
.onErrorReturn { false }