š”š Do you know how coroutineScope works in coroutines?
- Nikolay Miroshnychenko

- Dec 1, 2023
- 2 min read
As promised, this is the answer to the challenge that I posted 2 days agoĀ š§©
Here is the challenge:
Before I explain the answer - go ahead and take a look at the video š„.
I tried to build this UI to reflect what the code is doing "under the hood." š ļø I changed the delays to make it easier to understand, but the execution order is the same.
As you might have already understood - the tricky part here is the coroutineScope š¤. Initially, when I played around with this example, I was also surprised.
We have a coroutineScope, which is a suspending function, so why is task 4 not being run straight away? After all, suspending functions are supposed to be non-blocking.
Well, the biggest takeaway here is that a scope HAS to be finished before going further ā. This means that everything within that scope MUST complete before the outer scope (viewModelScope in our case) can proceed.
But it's a suspending function, so will it suspend once we encounter a delay()? ā²ļø Yep - but that doesn't mean other tasks in our viewModelScope will execute at that time.
Let's break down our order of execution:
1ļøā£ First, we have our Task 1. It's launched inside a separate coroutine via launch, and this coroutine is a child of our top-level viewModelScope. Task 1 launches immediately. Pretty easy.
2ļøā£ Next up is the "tricky part". Here, we create a coroutineScope. Inside we have a creation of another coroutine with launch { } with Task 2, which starts immediately, and immediately after that, we start Task 3. These are in the same scope - so tasks 2 and 3 are launched together.
3ļøā£ And finally, Task 4. Because we have a coroutineScope above, this task won't start before coroutineScope finishes.
This gives us an order of completion of 3 ā 1 ā 2 ā 4.
This is a trick question to make you understand what scopes do in coroutines š§ . Unless you're doing some heavy I/O work, you probably won't ever need to have a separate coroutineScope.
It's crucial to grasp this to understand how structured concurrency works.
Here is the code What is your experience of working with order of execution in Kotlin coroutines? Share your experience in the comments.







Comments