blob: ad0b02148814b1f03949ec436407c0b155ee8969 [file] [log] [blame]
Roman Elizarov32d95322017-02-09 15:57:31 +03001/*
Roman Elizarovdb0ef0c2019-07-03 15:02:44 +03002 * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarov32d95322017-02-09 15:57:31 +03003 */
4
5// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
Roman Elizarov0950dfa2018-07-13 10:33:25 +03006package kotlinx.coroutines.guide.compose04
Roman Elizarov32d95322017-02-09 15:57:31 +03007
Roman Elizarov0950dfa2018-07-13 10:33:25 +03008import kotlinx.coroutines.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +03009import kotlin.system.*
Roman Elizarov32d95322017-02-09 15:57:31 +030010
Inegoebe519a2019-04-21 13:22:27 +070011// note that we don't have `runBlocking` to the right of `main` in this example
Prendota65e6c8c2018-10-17 11:51:08 +030012fun main() {
Roman Elizarov32d95322017-02-09 15:57:31 +030013 val time = measureTimeMillis {
14 // we can initiate async actions outside of a coroutine
Marcin MoskaƂa7e94e702018-01-29 18:39:02 +010015 val one = somethingUsefulOneAsync()
16 val two = somethingUsefulTwoAsync()
Roman Elizarov32d95322017-02-09 15:57:31 +030017 // 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}
Prendota65e6c8c2018-10-17 11:51:08 +030025
26fun somethingUsefulOneAsync() = GlobalScope.async {
27 doSomethingUsefulOne()
28}
29
30fun somethingUsefulTwoAsync() = GlobalScope.async {
31 doSomethingUsefulTwo()
32}
33
34suspend fun doSomethingUsefulOne(): Int {
35 delay(1000L) // pretend we are doing something useful here
36 return 13
37}
38
39suspend fun doSomethingUsefulTwo(): Int {
40 delay(1000L) // pretend we are doing something useful here, too
41 return 29
42}