-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOkHttpAsyncCall.kt
48 lines (42 loc) · 1.4 KB
/
OkHttpAsyncCall.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okio.IOException
import kotlin.coroutines.resumeWithException
@ExperimentalCoroutinesApi
suspend fun Call.await(): Response {
return suspendCancellableCoroutine { continuation ->
enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
continuation.resume(response, onCancellation = null)
}
override fun onFailure(call: Call, e: IOException) {
if (continuation.isCancelled) return
continuation.resumeWithException(e)
}
})
continuation.invokeOnCancellation {
cancel()
}
}
}
fun Call.asFlow() = callbackFlow {
enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
trySendBlocking(response)
.onFailure { exception ->
if (exception != null)
throw exception.fillInStackTrace()
}
}
override fun onFailure(call: Call, e: IOException) {
cancel(call.request().url.toString(), e)
}
})
awaitClose()
}