如何在subscribeWith中使用ContextWrapper类

时间:2017-11-06 08:12:16

标签: android kotlin rx-java

您好我已经ContextWrapper在单个地方进行了改装错误处理,并希望在subscribeWith中使用它。

abstract class CallbackWrapper<T : BaseResponse> : DisposableObserver<T>() {

    protected abstract fun onSuccess(t: T)

    override fun onNext(t: T) {
        //You can return StatusCodes of different cases from your API and handle it here. I usually include these cases on BaseResponse and inherit it from every Response
        onSuccess(t)
    }

    override fun onError(e: Throwable) {
        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)
                }
            }
        }
    }


    override fun onComplete() {

    }

    private fun getErrorMessage(responseBody: ResponseBody): String {
        val jsonObject = JSONObject(responseBody.string())
        return jsonObject.getString(("message"))
    }
}

我试图像下面这样使用

ApiHelperImpl().doServerLoginApiCall(email, password)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(CallbackWrapper<LoginResponse> {

                    })

enter image description here

我想做https://blog.mindorks.com/rxjava2-and-retrofit2-error-handling-on-a-single-place-8daf720d42d6之类的事情有人知道怎么做吗?

1 个答案:

答案 0 :(得分:4)

您需要在()之后放置CallbackWrapper<LoginResponse>并在kotlin中实例化一个抽象类,您必须将其称为:object: AbstractClass(...params){}

ApiHelperImpl().doServerLoginApiCall(email, password)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(object: CallbackWrapper<LoginResponse>() {
        override fun onSuccess(r: LoginResponse) { }
    })