top of page

Do you know how scopes work in coroutines? 🤔





I've personally been confused by this topic for quite a while. But it's essential to understand how to correctly manage the execution of your concurrent tasks.


Say you need to run multiple concurrent operations at once. What would you prefer? Launching multiple coroutines via launch {} or asyncs{}? 🤷‍♂️ 


The correct answer depends on a couple of things. Most importantly, we need to know whether we expect some result from all of these operations.


Another question is - do other results matter if one of the operations fails or returns a wrong result? 


Take a look at the video. 📹 


When I'm launching "asyncs," - they're being launched within the same scope by a parent coroutine builder. You can't launch an async independently - it has to run in a scope.


After I cancel a single async - the other async gets canceled as well. Why?


Because of a thing called structured concurrency. 🏗 When encountering an exception from one of its children, the parent coroutine reacts by failing itself and canceling its other children. 😵


Compare this with Coroutine 1 and Coroutine 2


Cancelling does not influence the other in any way. Why? Because they're launched in separate unrelated scopes.


So, how do we answer the question of what should we choose? 


 ✅ As you can judge by the video - asyncs are better suited for tasks that need to complete and return a result together, while launching multiple coroutines works better for independent tasks.



What would you add here? Share your thoughts in the comment below.👇



83 views0 comments

Recent Posts

See All

留言


bottom of page