kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Doc: more documentation on cancellation needed

Open hrach opened this issue 7 years ago • 0 comments
trafficstars

Hi, I am/was quite struggling how is propagated cancelling to children/parent scopes. Commenting on Cancellation and timeouts.

  1. if the "execution" is paused on the await call, I was not sure it the execution continues. Finally I understood this falls under " All the suspending functions ... are cancellable". Maybe more emphasize this is also the case.
  2. There is no mention that when I can handle cancellation myself I don't have to throw CancellationException at the end. See printing "ending A" in example bellow, I was not sure at all, if it should not be followed by throwing an CancellationException.
  3. There is mention isActive is an extension property on CoroutineScope, but maybe a sample that in suspend function we should use couroutineScope builder to have it available would be useful. (If that's the proper way how to do this).

My test script to understand this

import kotlinx.coroutines.experimental.*

fun main(args: Array<String>) = runBlocking {
    val job = GlobalScope.launch {
        val sub1 = async {
            doSub1()
        }
        val sub2 = async {
            doSub2()
        }

        try {
            sub1.await()
        } catch (e: CancellationException) {}
        try {
            sub2.await()
        } catch (e: CancellationException) {
        }
        if (!isActive) {
            println("after await")
        }
    }
    delay(5000)
    job.cancelAndJoin()
}

suspend fun doSub1() = coroutineScope {
    while (isActive) {
        println("a")
        try {
            delay(100)
        } catch (e: CancellationException) {
        }
    }
    println("ending A")
}

suspend fun doSub2() = coroutineScope {
    while (isActive) {
        println("1")
        try {
            delay(300)
        } catch (e: CancellationException) {
        }
    }
    println("ending 1")
}

hrach avatar Oct 09 '18 07:10 hrach