Search⌘ K
AI Features

Connecting Coroutine Scope Functions

Explore how to combine Kotlin coroutine scope functions effectively to manage concurrency tasks. Understand why launching additional operations on separate scopes is beneficial and learn to create custom scopes like analyticsScope for nonessential processes. This lesson helps you handle coroutine cancellation and control suspending functions for improved asynchronous programming.

We'll cover the following...

If we need to use functionalities from two coroutine scope functions, we need to use one inside another. For instance, to set both a timeout and a dispatcher, we can use withTimeoutOrNull inside withContext.

Kotlin 1.5
suspend fun calculateAnswerOrNull(): User? =
withContext(Dispatchers.Default) {
withTimeoutOrNull(1000) {
calculateAnswer()
}
}

Additional operations

Imagine a case where we need to execute an additional operation during some processing. For example, after showing a user profile, we want to send a request for analytics purposes. People often do this with just a regular ...