In my retrofit + kotlin + RxJava setup I have added an adapter factory which looks into the response body and if it finds that a certain property does not have a certain value it converts the response into a custom exception.
Is there any way to get a similar result using only retrofit + kotlin coroutines?
Retrofit.addCallAdapterFactory(ErrorCheckingCallAdapterFactory())
class ErrorCheckingCallAdapterFactory() : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
if (CallAdapter.Factory.getRawType(returnType) != Single::class.java) {
return null // Ignore non-Observable types.
}
// Look up the next call adapter which would otherwise be used if this one was not present.
val delegate = retrofit.nextCallAdapter(this, returnType,
annotations) as CallAdapter<Any, Single<*>>
return object : CallAdapter<Any, Any> {
override fun adapt(call: Call<Any>): Any {
// Delegate to get the normal Observable...
val startTime = System.currentTimeMillis()
val o = delegate.adapt(call)
// ...and change it to send notifications to the observer on the specified scheduler.
return o.compose(errorCheckTransformer<Any>(startTime))
}
override fun responseType(): Type {
return delegate.responseType()
}
}
}
fun <T> errorCheckTransformer(startTime: Long): SingleTransformer<T, T> {
return SingleTransformer { observable ->
observable.flatMap { response ->
if (response is BaseResponse) {
if (!response.isSuccessful()) {
return@flatMap Single.error<T>(MemErrorException(response.result?.retCode, response.result?.retMsg, response))
}
}
Single.just(response)
}
}
}
}