Joost Klitsie
05/20/2021, 8:33 AMlifecycleScope
and I want to run some job that either runs after a certain time or event (so can get cancelled) what is the best way of doing so?
For example, using:
val job = supervisorJob()
val myScope = lifecycleScope + job
// Somewhere else
job.cancelChildren()
Is not working out, because the myScope
stays alive after the `lifecycleScope`is cancelled
Using
var job: Job? = null
val theWork = lifecycleScope.launch {
// delay, do the work
}
// Somewhere else
job?.cancel()
This would work, but then I always have to keep track of the job. Is it possible to have a lifecycle respecting scope on which I can cancel its children when necessary?Joost Klitsie
05/20/2021, 8:40 AMclass SupervisorScope(other: CoroutineScope): CoroutineScope {
private val job = SupervisorJob()
private val scope = other + job
override val coroutineContext: CoroutineContext
get() = scope.coroutineContext
init {
other.launch {
try {
awaitCancellation()
}
finally {
scope.cancel()
}
}
}
fun cancelChildren() {
job.cancelChildren()
}
}
Would this be a bad idea?Joost Klitsie
05/20/2021, 8:42 AMval supervisorScope = SupervisorScope(lifecycleScope)
supervisorScope.launch {
//...
}
supervisorScope.cancelChildren()
dshevliakov
05/20/2021, 12:59 PMdshevliakov
05/20/2021, 1:00 PMJoost Klitsie
05/20/2021, 1:00 PMJoost Klitsie
05/20/2021, 1:00 PMJoost Klitsie
05/20/2021, 1:01 PMdshevliakov
05/20/2021, 1:05 PMdshevliakov
05/20/2021, 1:05 PMdshevliakov
05/20/2021, 1:06 PMdshevliakov
05/20/2021, 1:07 PMJoost Klitsie
05/20/2021, 1:07 PMdshevliakov
05/20/2021, 1:09 PMdshevliakov
05/20/2021, 1:09 PMJoost Klitsie
05/20/2021, 1:11 PMJoost Klitsie
05/20/2021, 1:13 PMdshevliakov
05/20/2021, 1:13 PMJoost Klitsie
05/20/2021, 1:13 PMJoost Klitsie
05/20/2021, 1:13 PMdshevliakov
05/20/2021, 1:24 PMdshevliakov
05/20/2021, 1:31 PM