Concurrency with Coroutines in Android

Jun 5 2024 · Kotlin 1.9.23, Android 14, Android Studio Iguana

Lesson 04: Return Values

Demo

Episode complete

Play next episode

Next

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

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

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

Unlock now

Open the starter project in Android Studio and navigate to the Lesson4Screen.kt file. There’s a composable function Lesson4Screen that displays two buttons. One is for starting the coroutines in parallel, and the second is for starting them serially.

coroutineScope.async { doSomething(4) }
coroutineScope.async { doSomething(4) }
coroutineScope.async { doSomething(2) }
val deferredResults = listOf(
  coroutineScope.async { doSomething(4) },
  coroutineScope.async { doSomething(2) },
)
val deferredResults = listOf(
  coroutineScope.async { doSomething(4) },
  coroutineScope.async { doSomething(2) },
)
coroutineScope.launch {
  val result = measureTimedValue { deferredResults.awaitAll() }
  Log.i("Lesson4", "Parallel action results: ${result.value}, took: ${result.duration}")
}
coroutineScope.async {
  doSomething(2)
  throw RuntimeException("Test")
}
coroutineScope.launch {
  try {
    val result = measureTimedValue { deferredResults.awaitAll() }
    Log.i("Lesson4", "Parallel action results: ${result.value}, took: ${result.duration}")
  } catch (e: Exception) {
    Log.e("Lesson4", "Error in parallel actions", e)
    throw e
  }
}
coroutineScope.launch {
  val result = measureTimedValue {
    listOf(
      doSomething(4),
      doSomething(2),
    )
  }
  Log.i("Lesson4", "Serial Action results: ${result.value}, took: ${result.duration}")
}
async { doSomething(2) }.await()
See forum comments
Cinema mode Download course materials from Github
Previous: Instructions Next: Conclusion