【问题标题】:RxJava2 Flowable onErrorReturn not calledRxJava2 Flowable onErrorReturn 未调用
【发布时间】:2018-10-26 07:40:27
【问题描述】:

假设我需要用 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 应该能够在广播接收器中捕捉到 throw RuntimeException("Test exception"),但它没有捕捉到该异常和应用程序崩溃。

当然,我可以使用try/catch 在 BroadcastReceiver 中封装任何内容。但实际上,我那里有很多源代码,因此添加try/catch 会使源代码变得非常混乱。

有什么方法可以在一个地方捕获 Flowable 内任何一行中抛出的所有异常?

【问题讨论】:

    标签: exception kotlin exception-handling broadcastreceiver rx-java2


    【解决方案1】:

    如果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 }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多