Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | db0ef0c | 2019-07-03 15:02:44 +0300 | [diff] [blame] | 2 | * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 6 | package kotlinx.coroutines.guide.compose04 |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 7 | |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 8 | import kotlinx.coroutines.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 9 | import kotlin.system.* |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 10 | |
Inego | ebe519a | 2019-04-21 13:22:27 +0700 | [diff] [blame] | 11 | // note that we don't have `runBlocking` to the right of `main` in this example |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 12 | fun main() { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 13 | val time = measureTimeMillis { |
| 14 | // we can initiate async actions outside of a coroutine |
Marcin MoskaĆa | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 15 | val one = somethingUsefulOneAsync() |
| 16 | val two = somethingUsefulTwoAsync() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 17 | // but waiting for a result must involve either suspending or blocking. |
| 18 | // here we use `runBlocking { ... }` to block the main thread while waiting for the result |
| 19 | runBlocking { |
| 20 | println("The answer is ${one.await() + two.await()}") |
| 21 | } |
| 22 | } |
| 23 | println("Completed in $time ms") |
| 24 | } |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 25 | |
| 26 | fun somethingUsefulOneAsync() = GlobalScope.async { |
| 27 | doSomethingUsefulOne() |
| 28 | } |
| 29 | |
| 30 | fun somethingUsefulTwoAsync() = GlobalScope.async { |
| 31 | doSomethingUsefulTwo() |
| 32 | } |
| 33 | |
| 34 | suspend fun doSomethingUsefulOne(): Int { |
| 35 | delay(1000L) // pretend we are doing something useful here |
| 36 | return 13 |
| 37 | } |
| 38 | |
| 39 | suspend fun doSomethingUsefulTwo(): Int { |
| 40 | delay(1000L) // pretend we are doing something useful here, too |
| 41 | return 29 |
| 42 | } |