Skip to content

Commit ad6101d

Browse files
committed
OkHttp Call: split await() and awaitSuccess()
1 parent 0d742fe commit ad6101d

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

app/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,24 +64,22 @@ fun Call.asObservableWithAsyncStacktrace(): Observable<Pair<Exception, Response>
6464
fun Call.asObservable() = asObservableWithAsyncStacktrace().map { it.second }
6565

6666
// Based on https://github.com/gildor/kotlin-coroutines-okhttp
67-
suspend fun Call.await(): Response {
67+
private suspend fun Call.await(callStack: Array<StackTraceElement>): Response {
6868
return suspendCancellableCoroutine { continuation ->
69-
enqueue(object : Callback {
69+
val callback = object : Callback {
7070
override fun onResponse(call: Call, response: Response) {
71-
if (!response.isSuccessful) {
72-
continuation.resumeWithException(Exception("HTTP error ${response.code}"))
73-
return
74-
}
75-
76-
continuation.resume(response)
71+
continuation.resume(response) { response.body.close() }
7772
}
7873

7974
override fun onFailure(call: Call, e: IOException) {
8075
// Don't bother with resuming the continuation if it is already cancelled.
8176
if (continuation.isCancelled) return
77+
val exception = IOException(e).apply { stackTrace = callStack }
8278
continuation.resumeWithException(e)
8379
}
84-
})
80+
}
81+
82+
enqueue(callback)
8583

8684
continuation.invokeOnCancellation {
8785
try {
@@ -93,6 +91,20 @@ suspend fun Call.await(): Response {
9391
}
9492
}
9593

94+
suspend fun Call.await(): Response {
95+
val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
96+
return await(callStack)
97+
}
98+
99+
suspend fun Call.awaitSuccess(): Response {
100+
val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
101+
val response = await(callStack)
102+
if (!response.isSuccessful) {
103+
response.close()
104+
throw HttpException(response.code).apply { stackTrace = callStack }
105+
}
106+
return response
107+
}
96108
fun Call.asObservableSuccess(): Observable<Response> {
97109
return asObservableWithAsyncStacktrace().map { (asyncStacktrace, response) ->
98110
if (!response.isSuccessful) {
@@ -115,3 +127,5 @@ fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListene
115127

116128
return progressClient.newCall(request)
117129
}
130+
131+
class HttpException(val code: Int) : IllegalStateException("HTTP error $code")

0 commit comments

Comments
 (0)