States move in one direction only

Once a state has been reached, a job will not move back to a previous state. Consider the following application:

fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val job = launch {
delay(2000)
}

// Wait for it to complete once
job.join()

// Restart the Job
job.start()
job.join()
}
println("Took $time ms")
}

This code creates a job that suspends execution for 2 seconds. Once the job completes on the first call to job.join(), the start() function is called on job with the intent of restarting it, followed by a second call to join() to wait for the second execution to complete. The complete time of execution was measured and stored in the time variable.

Let's see how long the execution of this code takes:

As you can see, the total execution took around 2 seconds, which proves that job was executed only once. If calling start() on a complete job were to restart it, the total execution would have been around 4 seconds.

This is consistent with our previous statement—once a job has reached a state, it will not go back. In this case, the job reached a Completed state, so calling start() has no effect on it.

Likewise, calling join() in a complete job will not do anything. Since the job has already completed, no suspension will happen.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.93.132