June 2018
Intermediate to advanced
310 pages
6h 32m
English
What if we want to cancel more than one coroutine at the same time? That's where parent jobs come into play. Remember that launch() receives CoroutineContext, that's usually CommonPool? It can also receive other parameters, which will see shortly.
We'll start with a suspending function that works for some time:
suspend fun produceBeautifulUuid(): String { try { val uuids = List(1000) { yield() UUID.randomUUID() } println("Coroutine done") return uuids.sorted().first().toString() } catch (t: CancellationException) { println("Got cancelled") } return ""}
We would like to launch 10 of these and cancel them after only 100 ms.
For that, we'll use a parent job:
val parentJob = Job()List(10) { async(CommonPool + parentJob) { produceBeautifulUuid ...
Read now
Unlock full access