exception - RxJava2 Flowable onErrorReturn 未调用
问题描述
假设我需要BroadcastReceiver
用 Flowable 包装:
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
应该能够throw RuntimeException("Test exception")
在广播接收器中捕捉到它,但它没有捕捉到那个异常和应用程序崩溃。
当然,我可以在 BroadcastReceiver 中用try/catch
. 但实际上,我那里有很多源代码,因此添加try/catch
会使源代码非常混乱。
有没有办法在一个地方捕获 Flowable 内任何一行中抛出的所有异常?
解决方案
如果您有错误并希望通过流传递它,则需要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 }
推荐阅读
- javascript - 是否可以在 NPM 中使用两个不同版本的库?
- c++ - 如何从 C++(非阻塞)启动 macos .app?
- rust - 如何为嵌入在实现特征 A 或 B 的结构中的类型定义方法?
- bash - 为“git submodule foreach”设置不同的外壳
- java - 使用字符串值作为另一个变量的名称
- javascript - 它不会移动到下一个图像
- opencart - 如何让亚马逊 AWS 凭证在亚马逊卖家中心注册应用程序?
- python-3.x - 为码头保留空间时出现结构错误
- language-server-protocol - 自动化 LSP 交互以检测源代码
- html - Textarea scrollHeight 总是至少有两行的高度?