Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +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 | d4dcbe2 | 2017-02-22 09:57:46 +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.select04 |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 7 | |
Roman Elizarov | 9669578 | 2017-10-01 10:48:15 -0700 | [diff] [blame] | 8 | import kotlinx.coroutines.experimental.* |
| 9 | import kotlinx.coroutines.experimental.channels.* |
| 10 | import kotlinx.coroutines.experimental.selects.* |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 11 | import java.util.* |
| 12 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 13 | fun asyncString(time: Int) = async { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 14 | delay(time.toLong()) |
| 15 | "Waited for $time ms" |
| 16 | } |
| 17 | |
| 18 | fun asyncStringsList(): List<Deferred<String>> { |
| 19 | val random = Random(3) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 20 | return List(12) { asyncString(random.nextInt(1000)) } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 21 | } |
| 22 | |
| 23 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 24 | val list = asyncStringsList() |
| 25 | val result = select<String> { |
| 26 | list.withIndex().forEach { (index, deferred) -> |
| 27 | deferred.onAwait { answer -> |
| 28 | "Deferred $index produced answer '$answer'" |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | println(result) |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 33 | val countActive = list.count { it.isActive } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 34 | println("$countActive coroutines are still active") |
| 35 | } |