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

(cherry picked from commit 448702e5beedcd0918c504da34a0feda20ee2817)
This commit is contained in:
stevenyomi
2023-01-25 11:34:31 +08:00
committed by Jobobby04
parent 1948545983
commit a0497d079d
30 changed files with 158 additions and 184 deletions
@@ -1,17 +1,11 @@
package exh.util
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okhttp3.internal.closeQuietly
import rx.Observable
import rx.Producer
import rx.Subscription
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
fun Call.asObservableWithAsyncStacktrace(): Observable<Pair<Exception, Response>> {
// Record stacktrace at creation time for easier debugging
@@ -58,34 +52,3 @@ fun Call.asObservableWithAsyncStacktrace(): Observable<Pair<Exception, Response>
subscriber.setProducer(requestArbiter)
}
}
/**
* Similar to [Call.await] but it doesn't throw when the response is not successful
*/
suspend fun Call.awaitResponse(): Response {
return suspendCancellableCoroutine { continuation ->
enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
continuation.resume(response) {
response.closeQuietly()
}
}
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)
}
},
)
continuation.invokeOnCancellation {
try {
cancel()
} catch (ex: Throwable) {
// Ignore cancel exception
}
}
}
}