SuspendCoroutine
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Today I will be writing about the usage of an important concept in Android namely suspendCoroutine.
By definition suspendCoroutine helps us bridge the gap between callback based results(asynchronous) and coroutine block code.
Let us visualise a coroutine block executing a flow and the flow should only proceed ahead of a certain point only after that certain point completes its execution/purpose. And that certain point is where we are doing an api call which is as we know unpredictable in terms of its completion time - this is our use case.
In this case we tend to use something known as suspendCoroutine.
Now check the below code -
fun main() {
CoroutineScope(Dispatchers.IO).launch {
// some code
val result = suspendCoroutine<Pair<String, String>> { continuation ->
// api call
viewModel.uploadHomeWork(imageFileName) { url1, url2 ->
if (url1.isEmpty() || url2.isEmpty()) {
continuation.resume(Pair("", ""))
} else {
viewModel.uploadImage(url2, imageFile)
continuation.resume(Pair(url1, url2))
}
}
}
// some more code
// needs the url1 and url2 to proceed
}
}
In this case, we want to run some code before the api call and some more code after the api call. But the {// some more code} part needs data from the above api call to complete itself.
领英推荐
Inside the suspendCoroutine block, we receive a continuation object. This continuation acts as a state machine, meticulously tracking the status and state of the asynchronous operation. It holds the coroutine in a suspended state until the callback is invoked. Once the operation completes, the callback uses the continuation to resume the coroutine.
Further in case of any error in the api call we can resume the flow using resumeWithException().
For more clarity check the below source code -
I hope we learned something new today. Thanks for reading.
Do follow me for more such Android concepts.