zak.taccardi
01/04/2023, 10:15 PMprivate val onCleared = CompletableDeferred<Unit>()
init {
// logout in `onCleared()`
scope.job.invokeOnCompletion {
onCleared.complete(Unit)
}
scope.launch {
withContext(NonCancellable) {
onCleared.await()
// run a piece of suspending code when
// the `scope` above is cancelled
// (this correlates to a `ViewModel#onCleared`)
}
}
}
franztesca
01/04/2023, 11:15 PMwithContext
).
Scopes are not constrains that you need to workaround, are there to help you create structure in your code. Conceptually it doesn't make sense to execute code on a scope that is completed, so trying to make it happen is an anti pattern.
Consider using a scope that outlives the execution of your code, or if you want to opt out of structured concurrency just use GlobalScope. The proposed workaround is not better than GlobalScope.zak.taccardi
01/04/2023, 11:17 PMSam
01/05/2023, 8:34 AMscope.launch {
try {
awaitCancellation()
} finally {
withContext(NonCancellable) {
cleanup()
}
}
}