Concurrency with Coroutines in Android

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

Lesson 03: Understand Scope & Dispatchers

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. The demo projects for the previous lessons had a single screen. This time, there are multiple independent screens. One for the scopes and another for the dispatchers. You can navigate to one of them from the additional menu screen. There are also tests in the CoroutineTest class. Note it’s in the test directory, instead of in main as is the production code.

Dispatchers

Open the Lesson3DispatchersScreen file. It contains several buttons that start 100 coroutines on various dispatchers. Each coroutine suspends for ten milliseconds and then prints the message to the logcat with the current thread name. In this file, you won’t write any code but observe the logcat messages.

Using Scopes

Open the Lesson3ScopesScreen file. It contains several buttons that interact with the coroutine scopes. The CoroutineScope is created on top of the screen using the rememberCoroutineScope function. It’s the same function as used in the previous lesson. The created scope is bound to the lifetime of the screen composable. It’s canceled when the screen is removed from the composition. You’ll use that scope to launch all the coroutines in this exercise.

  coroutineScope.launch {
    Log.i("Lesson3", "starting 2 seconds delay")
    delay(2.seconds)
    Log.i("Lesson3", "navigating back")
    onNavigateBack()
  }
coroutineScope.launch {
  Log.d("Lesson3", "Coroutine started.")
  delay(2.seconds)
  Log.d("Lesson3", "Coroutine finished.")
}
Log.d("Lesson3", "Scope about to cancel.")
coroutineScope.cancel()
Log.d("Lesson3", "Scope cancellation requested.")
See forum comments
Cinema mode Download course materials from Github
Previous: Instructions Next: Conclusion