@@ -64,24 +64,22 @@ fun Call.asObservableWithAsyncStacktrace(): Observable<Pair<Exception, Response>
64
64
fun Call.asObservable () = asObservableWithAsyncStacktrace().map { it.second }
65
65
66
66
// 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 {
68
68
return suspendCancellableCoroutine { continuation ->
69
- enqueue( object : Callback {
69
+ val callback = object : Callback {
70
70
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() }
77
72
}
78
73
79
74
override fun onFailure (call : Call , e : IOException ) {
80
75
// Don't bother with resuming the continuation if it is already cancelled.
81
76
if (continuation.isCancelled) return
77
+ val exception = IOException (e).apply { stackTrace = callStack }
82
78
continuation.resumeWithException(e)
83
79
}
84
- })
80
+ }
81
+
82
+ enqueue(callback)
85
83
86
84
continuation.invokeOnCancellation {
87
85
try {
@@ -93,6 +91,20 @@ suspend fun Call.await(): Response {
93
91
}
94
92
}
95
93
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
+ }
96
108
fun Call.asObservableSuccess (): Observable <Response > {
97
109
return asObservableWithAsyncStacktrace().map { (asyncStacktrace, response) ->
98
110
if (! response.isSuccessful) {
@@ -115,3 +127,5 @@ fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListene
115
127
116
128
return progressClient.newCall(request)
117
129
}
130
+
131
+ class HttpException (val code : Int ) : IllegalStateException(" HTTP error $code " )
0 commit comments