Just found this channel after asking elsewhere.
# coroutines
e
Just found this channel after asking elsewhere.
m
I would avoid passing coroutine scopes to a function. The choice whether to launch a coroutine or make a function suspending depends on what the function is doing and what the responsibilities of the owner. You want most of your code async code to be in suspending functions so that you have the proper structured concurrency and that you get canceled when your caller does. But something somewhere needs to use the scope to start the work. In general I see that has belonging to the classes that have a lifecycle and the consumers don't care about their async work. For example with a Android app, I would have a view model or presenter launch jobs using a scope tied to its lifecycle. But the classes it uses to get the data such as a Repository would have suspending functions. The ViewModel is using a scope because it is doing work for itself. The repository has suspending functions because it is doing work for its callers. Now the ViewModel might still have some private suspending functions that it calls internally.
f
I agree for the most part, but not with this
I would avoid passing coroutine scopes to a function.
while using
suspend
functions is preferable, there is a pattern where you either extend
CoroutineScope
or pass the scope into the function, when the function launches a coroutine and returns immediately, without waiting for it to complete.
suspend
functions return when the work is complete, while functions extending
CoroutineScope
or accepting a scope return immediately
e
Thanks. The article spells out the rule: use suspend for functions that should run to completion:
If you need to launch a coroutine that keeps running after your function returns, then make your function an extension of
CoroutineScope
or pass
scope: CoroutineScope
as parameter to make your intent clear in your function signature. Do not make these functions suspending.
Suspending functions, on the other hand, are designed to be non-blocking and should not have side-effects of launching any concurrent work. Suspending functions can and should wait for all their work to complete before returning to the caller³.