Hello :wave: I was just wondering what is the idio...
# coroutines
d
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
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
yeah so that side effect would be app level scope
đź‘Ť
z
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
yeah it is just somewhat “odd” to have two scopes within a single function