【问题标题】:PublishSubject onError function in KotlinKotlin 中的 PublishSubject onError 函数
【发布时间】:2020-09-20 07:58:22
【问题描述】:

所以,当我尝试订阅 PublishSubject 时,我的 Android 应用 (Kotlin) 出现错误。

错误解释非常直截了当,但是,我尝试实现这个 onError 函数失败了,我不知道如何以上帝的方式做到这一点。

这里是错误

The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | com.androidnetworking.error.ANError

这里是发布主题:

var positionSubject = PublishSubject.create<Location>()

当我订阅时(在订阅代码中出现错误):

compositeDisposable.add(
                    positionSubject.subscribe {
                    // do some actions here that causes Exception
                    }
 )

我尝试以一种“不错”的方式修复它(没有用,订阅时仍然崩溃):

compositeDisposable.add(
                        positionSubject
                            .onErrorReturn { t -> 
                                 Log.d("debug", "EXCEPTION OCCURRED")
                                 Location("")}
                            .subscribe {
                        // do some actions here that causes Exception
                        }
     )

我最终做了什么来修复它而不是崩溃:

compositeDisposable.add(
                        positionSubject.subscribe {
                             try{
                                  // do some actions here that causes Exception
                             }catch(e:Exception){
                              Log.d("debug", "EXCEPTION OCCURRED $e")
                             }
                        
                        }
     )

如果可能的话,我想知道如何以一种比在订阅中使用 try/catch 块更简洁的方式来做到这一点。

【问题讨论】:

    标签: android kotlin publish-subscribe publishsubject


    【解决方案1】:

    以下代码是kotlin订阅PublishSubject的方式

    var positionSubject = PublishSubject.create<Location>()
    positionSubject.subscribe({ location ->
        
    }, { error ->
        
    })
    

    这应该可以正常工作。

    【讨论】:

    • 谢谢!这只是在 Kotlin 中正确编写它的问题!,它工作正常!
    猜你喜欢
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多