gpt4 book ai didi

android - 如何将 ContextWrapper 类与 subscribeWith 一起使用

转载 作者:搜寻专家 更新时间:2023-11-01 07:44:44 25 4
gpt4 key购买 nike

您好,我制作了 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 的事情有谁知道怎么做吗?

最佳答案

你需要把()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) { }
})

关于android - 如何将 ContextWrapper 类与 subscribeWith 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com