Skip to content

Instantly share code, notes, and snippets.

@mpierucci
Created July 16, 2021 13:01
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 mpierucci/3d5b914c93b2f3cacefc63e69e1824ac to your computer and use it in GitHub Desktop.
Save mpierucci/3d5b914c93b2f3cacefc63e69e1824ac to your computer and use it in GitHub Desktop.
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