https://kotlinlang.org logo
#android
Title
# android
h

Hele

06/26/2018, 6:52 PM
yeah I will definitely check them thanks
n

nwh

06/26/2018, 7:05 PM
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

gildor

06/27/2018, 3:21 AM
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

nwh

06/29/2018, 6:49 PM
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

gildor

06/30/2018, 4:05 AM
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