Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 6 | package kotlinx.coroutines.experimental.guide.context10 |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 7 | |
| 8 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 9 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 10 | |
| 11 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 12 | val job = Job() // create a job object to manage our lifecycle |
| 13 | // now launch ten coroutines for a demo, each working for a different time |
| 14 | val coroutines = List(10) { i -> |
| 15 | // they are all children of our job object |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 16 | launch(coroutineContext, parent = job) { // we use the context of main runBlocking thread, but with our parent job |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 17 | delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc |
| 18 | println("Coroutine $i is done") |
| 19 | } |
| 20 | } |
| 21 | println("Launched ${coroutines.size} coroutines") |
| 22 | delay(500L) // delay for half a second |
| 23 | println("Cancelling the job!") |
| 24 | job.cancelAndJoin() // cancel all our coroutines and wait for all of them to complete |
| 25 | } |