Improve OkHttp coroutines integration

master
Koitharu 8 months ago
parent b9ecdb2db6
commit 30f97c5c82
Signed by: Koitharu
GPG Key ID: 676DEE768C17A9D7

@ -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?

Loading…
Cancel
Save