Hi! Does anyone know why job2() is not running? Am...
# android
t
Hi! Does anyone know why job2() is not running? Am I doing something wrong?
Copy code
class MyViewModel:ViewModel() {
   private val job = SupervisorJob()
   private val scope = CoroutineScope(<http://Dispatcher.IO|Dispatcher.IO> + job)

   fun test() {
       viewModelScope.launch {
           job1()
           job.cancelAndJoin()
           scope.launch {
               job2()
           }
      }
  }
}
j
Hey, I’m not 100% sure, it has been a while since I used Coroutines extensively, but: I’m pretty sure it’s because you cancel the parent job (the one you pass to
CoroutineScope
) of the job you launch afterwards (the one containing
job2()
). Does it work if you remove the
job.cancelAndJoin()
line?
t
Yes it does. But I want to cancel jobs previously launched by that coroutine scope. What should I do in that case?
j
I guess you could either keep a reference to the job directly or cancel the scope and replace it with a new one for your new job.
Once canceled a scope is no longer active and you can not make it active again (as far as I know)
👍 1
j
can you try cancelChildren?
1
on the job
j
@Joost Klitsie I didn’t know that one, thx And I guess that should work
t
cancelChildren
works perfect. Thank you Joost and Johannes
👍 2
j
@Johannes Doll cancelchildren only works for supervisorjob, not the regular job, perhaps that is why 🙂 the power of supervisorjob is that it doesn't cancel if children get cancelled, as well as you can cancel the children