63.8 Coroutines – Suspending and Resuming
To gain a better understanding of coroutine suspension, it helps to see some examples of coroutines in action. To start with, let’s assume a simple Android app containing a button which, when clicked, calls a function named startTask(). It is the responsibility of this function to call a suspend function named performSlowTask() using the Main coroutine dispatcher. The code for this might read as follows:
private val myCoroutineScope = CoroutineScope(Dispatchers.Main)
fun startTask(view: View) {
myCoroutineScope.launch(Dispatchers.Main) {
performSlowTask()
}
}
In the above code, a custom scope is declared and referenced in the call to the launch builder which, in turn, calls the performSlowTask() suspend function. Note that since startTask() is not a suspend function, the coroutine must be started using the launch...