blob: beaf8f0e632c52f2b3006c5cb8788e2d95172037 [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarovf16fd272017-02-07 11:26:00 +03003 */
4
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03005// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
Roman Elizarova9687a32018-06-29 17:28:38 +03006package kotlinx.coroutines.experimental.guide.context06
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03007
Roman Elizarov7da42432017-11-20 11:57:58 +03008import kotlinx.coroutines.experimental.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +03009import kotlin.coroutines.experimental.*
Roman Elizarov2f6d7c92017-02-03 15:16:07 +030010
11fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov66f018c2017-09-29 21:39:03 +030012 // launch a coroutine to process some kind of incoming request
13 val request = launch {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +030014 // it spawns two other jobs, one with its separate context
Roman Elizarov66f018c2017-09-29 21:39:03 +030015 val job1 = launch {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +030016 println("job1: I have my own context and execute independently!")
17 delay(1000)
18 println("job1: I am not affected by cancellation of the request")
19 }
20 // and the other inherits the parent context
Roman Elizarov43e3af72017-07-21 16:01:31 +030021 val job2 = launch(coroutineContext) {
Roman Elizarov74619c12017-11-09 10:32:15 +030022 delay(100)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +030023 println("job2: I am a child of the request coroutine")
24 delay(1000)
25 println("job2: I will not execute this line if my parent request is cancelled")
26 }
27 // request completes when both its sub-jobs complete:
28 job1.join()
29 job2.join()
30 }
31 delay(500)
32 request.cancel() // cancel processing of the request
33 delay(1000) // delay a second to see what happens
34 println("main: Who has survived request cancellation?")
35}