android 如何在 rxjava2 中进行错误处理

How to do error handling in rxjava2 in android

您好,我在 android 应用程序中使用 RxJava2LiveData。我正在使用以下

进行 http 调用
@Inject
lateinit var retrofit: Retrofit

override fun doServerLoginApiCall(email: String, password: String): LiveData<LoginResponse> {
    val liveData = MutableLiveData<LoginResponse>()

    retrofit.create(RestApi::class.java).login(email, password)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { loginResponse ->
                liveData.setValue(loginResponse);
            }

    return liveData
} 

我如何处理上面代码中的错误。

when (e) {
    is HttpException -> {
        val responseBody = (e as HttpException).response().errorBody()
        responseBody?.let {
            view?.onUnknownError(getErrorMessage(it))
        }
    }
    is SocketTimeoutException -> {
        view?.onTimeout()
    }
    is IOException -> {
        view?.onNetworkError()
    }
    else -> {
        e.message?.let {
            view?.onUnknownError(it)
        }
    }
}

如果你想为你的订阅块实现 onError,你可以这样做:

retrofit.create(RestApi::class.java).login(email, password)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
                // success
                { loginResponse ->
                    liveData.setValue(loginResponse)
                },
                // error
                { e -> handleError(e) })

...

fun handleError(e: Throwable) {
    when (e) {
    ...
}