blob: 19dbdb843652514d8700240d6314959ace73dcdc [file] [log] [blame]
Roman Elizarovd4dcbe22017-02-22 09:57:46 +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 Elizarovd4dcbe22017-02-22 09:57:46 +03003 */
4
5// 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.select04
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03007
Roman Elizarov96695782017-10-01 10:48:15 -07008import kotlinx.coroutines.experimental.*
9import kotlinx.coroutines.experimental.channels.*
10import kotlinx.coroutines.experimental.selects.*
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030011import java.util.*
12
Roman Elizarov66f018c2017-09-29 21:39:03 +030013fun asyncString(time: Int) = async {
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030014 delay(time.toLong())
15 "Waited for $time ms"
16}
17
18fun asyncStringsList(): List<Deferred<String>> {
19 val random = Random(3)
Roman Elizarova84730b2017-02-22 11:58:50 +030020 return List(12) { asyncString(random.nextInt(1000)) }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030021}
22
23fun 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 Elizarov7c864d82017-02-27 10:17:50 +030033 val countActive = list.count { it.isActive }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030034 println("$countActive coroutines are still active")
35}