alexhelder
07/15/2025, 8:29 AMval job:Job? = null
fun foo() {
val oldJob = job
job = coroutinescope.launch {
oldJob?.cancelAndJoin()
}
}
Sam
07/15/2025, 8:42 AMDmitry Khalanskiy [JB]
07/15/2025, 9:22 AMjoin
and cancelAndJoin
both guarantee that they will wait for the body of the coroutine to complete, whether or not it was cancelled. However, invokeOnCompletion
blocks and the like are not guaranteed to run by the time join
exits.Zach Klippenstein (he/him) [MOD]
07/15/2025, 9:19 PMalexhelder
07/15/2025, 11:35 PMAtomicReference
be used for oldJob
since its being assigned in one spot, but referenced (for cancel) in the new coroutine? If you have any snippets of this pattern I’d be interested in studying them.alexhelder
07/16/2025, 10:19 AMAtomicReference
val externalScope : CoroutineScope = ...
val currentJob = AtomicReference<Job?>(null)
fun foo(...) {
externalScope.launch {
currentJob.getAndSet(coroutineContext.job)?.cancelAndJoin()
... do things ...
}
}
}