Improve OkHttp coroutines integration
This commit is contained in:
@@ -5,32 +5,30 @@ import kotlinx.coroutines.CompletionHandler
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.Response
|
||||
import okhttp3.internal.closeQuietly
|
||||
import java.io.IOException
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
internal class ContinuationCallCallback(
|
||||
private val call: Call,
|
||||
private val continuation: CancellableContinuation<Response>,
|
||||
private val call: Call,
|
||||
private val continuation: CancellableContinuation<Response>,
|
||||
) : Callback, CompletionHandler {
|
||||
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
if (continuation.isActive) {
|
||||
continuation.resume(response)
|
||||
}
|
||||
}
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
continuation.resume(response) { _, value, _ ->
|
||||
value.closeQuietly()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
if (!call.isCanceled() && continuation.isActive) {
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
}
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
|
||||
override fun invoke(cause: Throwable?) {
|
||||
runCatching {
|
||||
call.cancel()
|
||||
}.onFailure { e ->
|
||||
cause?.addSuppressed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun invoke(cause: Throwable?) {
|
||||
runCatching {
|
||||
call.cancel()
|
||||
}.onFailure { e ->
|
||||
cause?.addSuppressed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import kotlin.contracts.contract
|
||||
|
||||
public suspend fun Call.await(): Response = suspendCancellableCoroutine { continuation ->
|
||||
val callback = ContinuationCallCallback(this, continuation)
|
||||
enqueue(callback)
|
||||
continuation.invokeOnCancellation(callback)
|
||||
enqueue(callback)
|
||||
}
|
||||
|
||||
public val Response.mimeType: String?
|
||||
|
||||
Reference in New Issue
Block a user