Created
July 14, 2022 00:57
-
-
Save SamueldaCostaAraujoNunes/3976313869643fb9934f2262f561d299 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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