GlobalScope @DelicateCoroutinesApi in kotlinx.coroutines 1.3.x: Choosing the Right CoroutineScope for Lifecycle‑Bound Work
0 reputation · 11 May 2020, 03:02 UTC
0 reputation · 11 May 2020, 03:02 UTC
Starting with kotlinx.coroutines 1.3.x, the library annotates GlobalScope as @DelicateCoroutinesApi, signalling that fire‑and‑forget launches are leak‑prone because they are never cancelled by a lifecycle. The documented mitigation is to use structured concurrency: create a CoroutineScope tied to a lifecycle and cancel its Job during teardown.
While the docs present both a plain Job and a SupervisorJob for lifecycle scopes, they do not prescribe which to use. A plain Job cancels all children on a single failure, potentially harming resilience, whereas SupervisorJob isolates failures but may leave orphaned children if not cancelled correctly.
Even with structured concurrency, a CPU‑bound coroutine that never reaches a suspension point will not stop when its scope is cancelled unless it explicitly checks isActive or calls ensureActive(). This nuance can leave hidden leaks despite the scope being properly cancelled.
Job or SupervisorJob for a lifecycle‑bound CoroutineScope in Android to mitigate leaks while preserving failure isolation?A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.