【问题标题】:Handle response.body == null in RX处理 RX 中的 response.body == null
【发布时间】:2021-12-25 19:49:09
【问题描述】:

我在下面的android中使用Rx

        repository.getUserList()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->

                val userList = response.body()!!
                view.showUser(userList)
                
            }, { throwable ->
                handlerException(view, throwable)
            }).addToDisposable()

有效。

但有时response.body() 为空,可能是网络错误或服务器没有响应, 那么应用就会崩溃。

所以我必须像这样添加try catch

        repository.getUserList()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->

                try {
                    val userList = response.body()!!
                    view.showUser(userList)
                } catch (e: Exception) {
                    handleException(view, e)
                }
            }, { throwable ->
                handleException(view, throwable)
            }).addToDisposable()

但我认为应该有更好的方法来处理 rx 中的错误。 谁能帮帮我,谢谢。

【问题讨论】:

    标签: android kotlin error-handling rx-java rx-android


    【解决方案1】:

    你可以使用过滤运算符

    .filter { it != null }
    

    这是 RX 方式,但您可以像这样使用 kotlin 空安全:

    .subscribe({ response ->
    
                response.body()?.let{
                view.showUser(userList)
                  }
            }
    

    希望对你有所帮助??

    【讨论】:

    • 谢谢。但我认为它和try catch 一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    相关资源
    最近更新 更多