Skip to content

Instantly share code, notes, and snippets.

@SamueldaCostaAraujoNunes
Created July 14, 2022 00:57
Show Gist options
  • Save SamueldaCostaAraujoNunes/3976313869643fb9934f2262f561d299 to your computer and use it in GitHub Desktop.
Save SamueldaCostaAraujoNunes/3976313869643fb9934f2262f561d299 to your computer and use it in GitHub Desktop.
class FlowResultCallAdapter<R>(
private val responseType: Type,
private val annotations: Array<out Annotation>
) : CallAdapter<R, Flow<Result<R>>> {
override fun adapt(call: Call<R>): Flow<Result<R>> {
return flow {
emit(
suspendCancellableCoroutine { continuation ->
call.clone().enqueue(object : Callback<R> {
override fun onResponse(call: Call<R>, response: Response<R>) {
val statusCode = response.code()
continuation.resume(
if (response.isSuccessful) {
val body = response.body()
if (body == null || statusCode == 204) {
Result.Empty()
} else {
Result.Success(
data = body,
statusCode = statusCode
)
}
} else {
val errorResponse = parseError(
statusCode = statusCode,
responseBody = response.errorBody(),
annotations = annotations
)
Result.Error(
message = response.message(),
statusCode = statusCode,
errorResponse = errorResponse
)
}
)
}
override fun onFailure(call: Call<R>, throwable: Throwable) {
continuation.resume(Result.Error(throwable))
}
})
continuation.invokeOnCancellation { call.cancel() }
}
)
}
}
override fun responseType() = responseType
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment