Follow my public account “ananzhuo” to learn more knowledge

Coroutines are written in four parts

Coroutine porter – Context and scheduler

Coroutine porter – Composite suspend functions

Coroutine Porter – Cancel with timeout

Coroutine porter – Basic

The cancellation of the Job

There’s probably a situation in development where we’re doing a 2s task in a page coroutine to get the data, get the data and successfully present the UI. However, there may be a case that our page is returned by the user after the execution of the coroutine 1s, and the data requested in the coroutine is no longer needed, so we need to remove the coroutine.

The job in the following code can be cancelled

  1. code
fun main() = runBlocking {
    val job: Job = launch {
        repeat(20) {//A
            log(A)
            delay(500)//B
            log(B)
        }
    }
    delay(1700)//C
    job.cancel()//D
}
Copy the code
  1. The log
Log: A log: B Log: A log: B log: A log: B log: ACopy the code
  1. conclusion

The coroutine can be fetched after the launch coroutine body calls Cancel

Cancellation of coroutines is collaborative

  1. What we mean by collaboration here is that if the coroutine is executing a time-consuming task internally, then even if we cancel the coroutine, we need to complete the calculation to actually cancel it

  2. If you use a suspend function internally, you can immediately respond to the cancellation as follows:

Fun main() = runBlocking {val job = launch(dispatchers.default) {work()} delay(1300L) Job.cancelandjoin () // Cancels a job and waits for it to end log(C)} suspend fun work() {delay(10)}Copy the code

The above code runs a work suspension function inside the launch method, so when we cancel elandJoin, the coroutine is cancelled immediately. 3. If you are computation-intensive and can’t get the coroutine, there are other ways to do it. For example, we can periodically check Job. IsActive to determine whether the coroutine isActive to decide whether to terminate the computation. After the cancel isActive = = false

timeout

WithTimeOut or withTimeOutOrNull can respond to a timeout

Here are two methods

withTimeOut

Crashes when withTimeOut times out

  1. code
Fun main() = runBlocking {val result = withTimeout(3*1000){// Repeat (20){ } log(result) delay(100)}Copy the code
  1. The log
Log: A log: A log: A Exception in the thread "main" kotlinx coroutines. TimeoutCancellationException: Timed out waiting for 3000 msCopy the code
  1. conclusion

WithTimeOut can respond to a timeout, and a crash log is reported when a timeout occurs

withTimeOutOrNull

WithTimeOutOrNull will not crash, and a timeout will return NULL 1. code

Make a small change to the previous example

Fun main() = runBlocking {val result = withTimeoutOrNull(3*1000){repeat(20){log(A) delay(1000)} "end of repeat"} log(result? Delay (100)}Copy the code
  1. The log
Log: A Log: A log: A log: No result was generated due to timeoutCopy the code
  1. conclusion

WithTimeOutOrNull Timeout is not an error and will return NULL