Skip to content

Instantly share code, notes, and snippets.

@mpierucci
Created Jul 16, 2021
Embed
What would you like to do?
Simple EitherCall example for retrofit
internal class EitherCall<R>(
private val delegate: Call<R>,
private val successType: Type
) : Call<Either<Failure, R>> {
override fun clone(): Call<Either<Failure, R>> {
TODO("Not yet implemented")
}
override fun execute(): Response<Either<Failure, R>> {
TODO("Not yet implemented")
}
override fun enqueue(callback: Callback<Either<Failure, R>>) {
return delegate.enqueue(
object : Callback<R> {
override fun onResponse(call: Call<R>, response: Response<R>) {
callback.onResponse(
this@EitherCall,
Response.success(response.toEither(successType))
)
}
//Called when connection with the server error NOT on 400..500
override fun onFailure(call: Call<R>, throwable: Throwable) {
val failure = when (throwable) {
is NoConnectionException, is IOException -> Failure.NetworkConnection
else -> Failure.Unknown
}
callback.onResponse(
this@EitherCall,
Response.success(failure.left())
) // either left for failure
}
}
)
}
override fun isExecuted(): Boolean = delegate.isExecuted
override fun cancel() {
delegate.cancel()
}
override fun isCanceled(): Boolean = delegate.isCanceled
override fun request(): Request {
return delegate.request()
}
override fun timeout(): Timeout {
return delegate.timeout()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment