How would I add cleanup code to a `CoroutineScope`...
# coroutines
r
How would I add cleanup code to a
CoroutineScope
to be executed when
cancel()
is invoked on it?
j
Copy code
scope.launch {
  try {
    awaitCancelation()
  } finally {
    doCleanup()
  }
}
r
Thanks. Tried with
connectionScope.coroutineContext.job.invokeOnCompletion
, that didn't catch
j
although that will keep the scope alive, so you basically have to call
cancel()
on it both in the success path and any early-exit paths
z
If you're in a parent of the scope you're waiting for, you could just join on the child job
d
Jake's suggestion is good, but you may need to call
launch
like this:
scope.launch(start = CoroutineStart.ATOMIC) {
. Otherwise, cancellation can happen before the cleanup coroutine is started, so the cleanup code will never run.