OkHttp Call: split await() and awaitSuccess() (#8980)

This commit is contained in:
stevenyomi
2023-01-25 11:34:31 +08:00
committed by GitHub
parent 2ef1f07aae
commit 448702e5be
12 changed files with 86 additions and 75 deletions

View File

@ -65,16 +65,11 @@ fun Call.asObservable(): Observable<Response> {
// Based on https://github.com/gildor/kotlin-coroutines-okhttp
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun Call.await(): Response {
private suspend fun Call.await(callStack: Array<StackTraceElement>): Response {
return suspendCancellableCoroutine { continuation ->
enqueue(
val callback =
object : Callback {
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
continuation.resumeWithException(HttpException(response.code))
return
}
continuation.resume(response) {
response.body.close()
}
@ -83,11 +78,12 @@ suspend fun Call.await(): Response {
override fun onFailure(call: Call, e: IOException) {
// Don't bother with resuming the continuation if it is already cancelled.
if (continuation.isCancelled) return
continuation.resumeWithException(e)
val exception = IOException(e).apply { stackTrace = callStack }
continuation.resumeWithException(exception)
}
},
)
}
enqueue(callback)
continuation.invokeOnCancellation {
try {
@ -99,6 +95,21 @@ suspend fun Call.await(): Response {
}
}
suspend fun Call.await(): Response {
val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
return await(callStack)
}
suspend fun Call.awaitSuccess(): Response {
val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
val response = await(callStack)
if (!response.isSuccessful) {
response.close()
throw HttpException(response.code).apply { stackTrace = callStack }
}
return response
}
fun Call.asObservableSuccess(): Observable<Response> {
return asObservable().doOnNext { response ->
if (!response.isSuccessful) {