[英]RxJava2 Error Handling Wrapper For Retrofit Service
我需要在我的網絡服務應用程序中全局處理錯誤,我在改造服務中使用Rxjava2CallAdapterFactory。 因此,為了在全球范圍內處理錯誤,我在各個站點進行了搜索,並找到了解決方案。 但是我確實知道這是如何工作的。
class RxErrorAdapter private constructor() : CallAdapter.Factory() {
private val original = RxJava2CallAdapterFactory.create()
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
return Wrapper<Any>(original.get(returnType, annotations, retrofit)
?: return null)
}
private class Wrapper<R>(private val wrapped: CallAdapter<R, *>) : CallAdapter<R, Any> {
override fun responseType(): Type {
return wrapped.responseType()
}
override fun adapt(call: Call<R>): Any {
val result = wrapped.adapt(call)
}
}
companion object {
fun create(): CallAdapter.Factory {
return RxErrorAdapter()
}
}
}
有人可以解釋嗎?
由於RxJava2CallAdapter
已經知道如何去適應一個返回類型Call<T>
以Observable<T>
Completable
和其他的Rx類型, RxErrorCallAdapterFactory
詢問原廠RxJava2CallAdapterFactory
來創建這樣的“原始” RxJava2CallAdapter
。 然后, RxErrorCallAdapterFactory
創建其自己的CallAdapter
- RxCallAdapterWrapper
,並在其中包含原始適配器。
所以RxErrorCallAdapterFactory
給出RxCallAdapterWrapper
首先代表原來的哪個RxJava2CallAdapter
轉換Call<User>
,以Observable<User>
,然后應用onErrorResumeNext()
操作ontop的的Observable<User>
。
當在網絡請求期間發生錯誤時(例如,來自服務器的400錯誤請求),該錯誤將傳播到onErrorResumeNext()
,您可以在其中應用錯誤映射邏輯。 在這種情況下, onErrorResumeNext()
獲取Throwable
並返回Observable
,該信號指示已映射Throwable
onError()
。
基本上,如果原始CallApater
返回Observable.just(User())
,則包裝器CallAdapter
將返回以下內容:
Observable.just(User())
.onErrorResumeNext { throwable ->
Observable.error(map(throwable))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.