https://kotlinlang.org logo
#coroutines
Title
# coroutines
w

winchester044

08/14/2019, 10:55 AM
Hi folks, I was wondering if there is a way to cancel/stop `runBlocking`(which has an associated context) once the parent job is cancelled and the lambda is yet to start execution on the underlying dispatcher? Consider example:
Copy code
class Foo {
    val dispatcher// An android handler thread as a Coroutine Dispatcher
    val job // Parent Job
    val coroutineScope = job + dispatcher

    fun <T> run(block: () -> T) {
        // some prechecks
        return runBlocking(coroutinScope.coroutineContext) {
            // this runs on dispatcher
        }
    }

    fun shutdown() {
       // stop underlying runBlocking 
       job.cancel()
    }
}
Consider the handler thread is busy doing some other stuff and
runBlocking
is waiting for it to finish. Meanwhile
shutdown()
gets invoked. Is there a way to 'cancel/stop' this
runBlocking
call? (Without using thread interrupts, although once lambda has started execution cancellation becomes cooperative).
m

Melih Aksoy

08/14/2019, 1:44 PM
Is this before it’s reached or after it starts doing some work but before completes ?
AFAIK
runBlocking
will be cancelled with context you provide and end up with
JobCancellationException
.
w

winchester044

08/14/2019, 2:19 PM
Its after control reaches
runBlocking
and current thread is blocked. But
runBlocking
is waiting for the dispatcher to become free (its busy doing something else), so, 'actual' execution is yet to start.