65.9 Returning Results from a Coroutine
The above example ran a suspend function as a coroutine but did not demonstrate how to return results. Suppose, however, that the performSlowTask() function is required to return a string value which is to be displayed to the user via a TextView object.
To do this, we need to rewrite the suspend function to return a Deferred object. A Deferred object is essentially a commitment to provide a value at some point in the future. By calling the await() function on the Deferred object, the Kotlin runtime will deliver the value when it is returned by the coroutine. The code in our startTask() function might, therefore, be rewritten as follows:
fun startTask(view: View) {
coroutineScope.launch(Dispatchers.Main) {
statusText.text = performSlowTask().await()
}
}
The problem now is that we are having to use the launch builder to start the coroutine...