yeah I will definitely check them thanks
# android
h
yeah I will definitely check them thanks
n
If you do, here is a little convenience method for you
Copy code
/**
 * Dispatches a `GET` request to this URL and returns the resulting body as a string, or `null`
 * if no body was returned.
 */
suspend fun URL.text() = suspendCoroutine<String?> {
	val call = okHttp.newCall(Request.Builder().url(this@text).get().build())
	call.enqueue(object: Callback {
		override fun onFailure(call: Call, e: IOException) {
			it.resumeWithException(e)
		}
		override fun onResponse(call: Call, response: Response) {
			val body = response.body()!!
			it.resume(body.string())
		}
	})
}
g
Your implementation doesn’t handle cancellation Please check this implementation, it’s more correct https://github.com/gildor/kotlin-coroutines-okhttp/blob/master/src/main/kotlin/ru/gildor/coroutines/okhttp/CallAwait.kt
You also can convert it to extension function for url
n
Interesting, had never seen how to work with cancellation like that. Thanks!
Why do you check if it's cancelled on error but not on response?
g
Without support of cancellation such request will temporary leak (until request result) and also you cannot cancel some big or slow request
@nwh There is check for cancelled because if coroutine cancelled, invokeOnCompletion also cancel request and request will invoke onError callback, but because coroutine already cancelled and return Cancellation Exception, you cannot replace error cause with a new one From other side it's highly doubtful that onSuccess will return to cancelled coroutine, because of coroutine cancelled, request also will be cancelled