Instructions

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Async & Await

To be able to return a value from a coroutine, you need to use the async coroutine builder. The launch coroutine builder is unsuitable for this purpose because it returns a Job object, which doesn’t provide a way to get the result of the coroutine.

suspend fun fetchAndProcessData() = coroutineScope { 
  val deferred1 = async { fetchData1() }
  val deferred2 = async { fetchData2() }
  val data = awaitAll(deferred1, deferred2)
  processData(data)
}
listOf(deferred1, deferred2).map { it.await() }
Veruoteba #9 vumc dadfevut ivaatUwk mookp Minaudipe #2 Dahaozawo #9 Curiaxevi #6 fuulw Kuzaenove #1 Bekeasore #4 kaxfilioj Qiyeevaju #6 Gupuizuqi #7 fuemt Mokaik az amiuf kaarm

MainScope().launch { throw RuntimeException("Test") } // 1
MainScope().async { throw RuntimeException("Test") } // 2
MainScope().launch {
  async { throw RuntimeException("Test") } // 3
}
async(start = CoroutineStart.LAZY) { doSomething() }

Using coroutineScope & supervisorScope

The coroutineScope and supervisorScope functions you’ve already seen in the previous lesson can return values. The difference between them and the async builder is that they are suspending functions. So, you can use them only in suspending functions or coroutines.

runBlocking

The runBlocking coroutine builder also returns a value. It may be useful to bridge the suspendable world with the blocking world. For example, you can use it to run the suspending function in the non-suspending function provided by some external library, which you can’t change to be suspending. This is commonly seen when mixing and matching between callback-based codebases and coroutines, or when working with Java.

suspendCoroutine & suspendCancellableCoroutine

Similar to runBlocking, you can use suspendCoroutine and suspendCancellableCoroutine functions to connect the callback-based API with the coroutine world. Imagine that you’re using a library that provides a callback-based API to get the humidity from a sensor. You can wrap this API with suspendCancellableCoroutine.

val currentHumidity = suspendCancellableCoroutine<Int> { continuation -> 
  continuation.invokeOnCancellation { humidityService.stop() }
  
  humidityService.getCurrentHumidity()
   .addOnSuccessListener { humidity -> continuation.resume(humidity) }
   .addOnFailureListener { error -> continuation.resumeWithException(error) }
   .addOnCanceledListener { continuation.cancel() }
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo