How to relaunch cancelled Job?

Viewed 2504

I want to use coroutines instead of handlers. I have call which will refresh data every few seconds. It is called in Job object. When I leave app to background, I want to cancel this Job. When I come back to app I want to relaunch this job to do its work.

But once I cancel job, it will not relaunch ever again. Is there any way how to relaunch cancelled job? Because isActive == false even when I reinitialize variable

var job: Job? = null

job = launch {
    while (isActive){
    delay(5000)
    doStuff()
    }
}

When I pause my Activity I call job?.cancel() and job = null When I enter Activity, I will call code above again. I thought I can reinitialize this job and launch refresh code again.

2 Answers

There is no way to restart a cancel()ed job. But this is easy enough to work around. Just start a new job instead. You could do it like this:

fun launchNewJob() = launch {
    while (isActive) {
        delay(5000)
        doStuff()
    }
}

job = launchNewJob()

Jobs/coroutines are not heavy objects like Threads, so you don't need to worry about creating new ones.

You can't "re-launch" the Job but you can create a new one, when you wrap the code inside:

var job = launch { jobFunction() }

fun jobFunction() {
    while (isActive){
      delay(5000)
      doStuff()
    }
}

if(job.isActive.not()) {
  job = launch( jobFunction() )
}
Related