Skip to content

Instantly share code, notes, and snippets.

@naturalwarren
Last active January 9, 2019 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naturalwarren/3d7f1f4d869ab6c09f9a92f2a5dc3a0c to your computer and use it in GitHub Desktop.
Save naturalwarren/3d7f1f4d869ab6c09f9a92f2a5dc3a0c to your computer and use it in GitHub Desktop.
/**
* Decorates stream emissions from [delegateAdapter] in [CoinbaseResponse].
*/
internal class CoinbaseRxJava2CallAdapter(
private val successBodyType: Type,
private val delegateAdapter: CallAdapter<Any, Any>,
private val errorConverter: Converter<ResponseBody, Any?>,
private val supportedType: SupportedType<Any, Any>
) : CallAdapter<Any, Any> {
override fun adapt(call: Call<Any>): Any {
val stream = delegateAdapter.adapt(call) //ie Single<AccessToken>
// Turn all types to an Observable. ie Observable<AccesToken>
val coinbaseStream = supportedType.toObservable(stream)
.map { response ->
when {
response.isSuccessful -> CoinbaseResponse<Any, Any>(
response,
response.errorBody(),
null
)
else -> {
val error = response.errorBody()
val errorBody = when {
error == null -> null
error.contentLength() == 0L -> null
else -> errorConverter.convert(error)
}
CoinbaseResponse(
response,
errorBody,
null
)
}
}
}.onErrorResumeNext(
Function<Throwable, Observable<CoinbaseResponse<Any, Any>>> { throwable ->
val response: CoinbaseResponse<Any, Any> = CoinbaseResponse(
null,
null,
throwable as IOException
)
Observable.just(response)
})
return supportedType.fromObservable(coinbaseStream)
}
override fun responseType(): Type = successBodyType
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment