首页 > 解决方案 > 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 内任何一行中抛出的所有异常?

标签: exceptionkotlinexception-handlingbroadcastreceiverrx-java2

解决方案


如果您有错误并希望通过流传递它,则需要Flowable#create()遵循合同,您需要捕获它并调用. 如果你这样做,就会按预期开始工作。Flowableemitter.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 }

推荐阅读