https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dariusz Kuc

12/11/2020, 4:45 PM
Hello 👋 I was just wondering what is the idiomatic way to launch some side effects from main coroutine whose return value doesn’t depend on it (i.e. side effect can take some time to complete and it is fine if that computation fail) so that it actually does not have to wait for its completion, e.g. given something simple like below
Copy code
suspend fun doWork() = coroutineScope {
  val result = ...
  // do some other processing that calculates/processes result

  publishData(result) // optional stuff that may be slow, e.g. publish analytics, debug info, etc
  result
}
Thanks to structured concurrency if I launch another coroutine from the
doWork
, all the child coroutines (including
publishData
from above) have to complete before returning from the scope. I could obviously just do
GlobalScope.launch { publishData }
but that seems “wrong”. Wondering whether instead I should be using something like buffered
Channel
so publish is async and data is processed in another coroutine. Or maybe there is something simpler?
z

Zach Klippenstein (he/him) [MOD]

12/11/2020, 4:47 PM
This is the same question whether or not you’re launching from a suspend function or not. Figure out what is the correct scope for the work, pass that scope in or inject it somehow, and use that scope to launch the side effect coroutine.
d

Dariusz Kuc

12/11/2020, 5:01 PM
yeah so that side effect would be app level scope
👍
z

Zach Klippenstein (he/him) [MOD]

12/11/2020, 5:37 PM
Makes sense. Note that even when the scope is the app-level scope, it’s still a good practice to inject the scope. It makes everything more explicit, easier to refactor later, easier to control in tests, etc. etc.
d

Dariusz Kuc

12/11/2020, 5:56 PM
yeah it is just somewhat “odd” to have two scopes within a single function
5 Views