select 表达式可以同时等待多个挂起函数,并 选择 第一个可用的。

    我们现在有两个字符串生产者:fizzbuzz 。其中 fizz 每 300 毫秒生成一个“Fizz”字符串:

    接着 buzz 每 500 毫秒生成一个 “Buzz!” 字符串:

    1. fun CoroutineScope.buzz() = produce<String> {
    2. while (true) { // 每 500 毫秒发送一个"Buzz!"
    3. delay(500)
    4. send("Buzz!")
    5. }
    6. }

    使用 挂起函数,我们可以从两个通道接收 其中一个 的数据。 但是 select 表达式允许我们使用其 子句 同时 从两者接收:

    1. suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
    2. select<Unit> { // <Unit> 意味着该 select 表达式不返回任何结果
    3. fizz.onReceive { value -> // 这是第一个 select 子句
    4. println("fizz -> '$value'")
    5. }
    6. buzz.onReceive { value -> // 这是第二个 select 子句
    7. println("buzz -> '$value'")
    8. }
    9. }
    10. }

    让我们运行代码 7 次:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.channels.*
    3. import kotlinx.coroutines.selects.*
    4. fun CoroutineScope.fizz() = produce<String> {
    5. while (true) { // 每 300 毫秒发送一个 "Fizz"
    6. delay(300)
    7. send("Fizz")
    8. }
    9. }
    10. fun CoroutineScope.buzz() = produce<String> {
    11. while (true) { // 每 500 毫秒发送一个 "Buzz!"
    12. delay(500)
    13. send("Buzz!")
    14. }
    15. }
    16. suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
    17. select<Unit> { // <Unit> 意味着该 select 表达式不返回任何结果
    18. fizz.onReceive { value -> // 这是第一个 select 子句
    19. println("fizz -> '$value'")
    20. }
    21. buzz.onReceive { value -> // 这是第二个 select 子句
    22. println("buzz -> '$value'")
    23. }
    24. }
    25. }
    26. fun main() = runBlocking<Unit> {
    27. //sampleStart
    28. val fizz = fizz()
    29. val buzz = buzz()
    30. repeat(7) {
    31. selectFizzBuzz(fizz, buzz)
    32. }
    33. coroutineContext.cancelChildren() // 取消 fizz 和 buzz 协程
    34. //sampleEnd
    35. }

    可以在这里获取完整代码。

    这段代码的执行结果如下:

    1. fizz -> 'Fizz'
    2. buzz -> 'Buzz!'
    3. fizz -> 'Fizz'
    4. fizz -> 'Fizz'
    5. buzz -> 'Buzz!'
    6. fizz -> 'Fizz'
    7. buzz -> 'Buzz!'

    select 中的 子句在已经关闭的通道执行会发生失败,并导致相应的 select 抛出异常。我们可以使用 onReceiveOrNull 子句在关闭通道时执行特定操作。以下示例还显示了 select 是一个返回其查询方法结果的表达式:

    1. suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
    2. select<String> {
    3. a.onReceiveOrNull { value ->
    4. if (value == null)
    5. "Channel 'a' is closed"
    6. else
    7. "a -> '$value'"
    8. }
    9. b.onReceiveOrNull { value ->
    10. if (value == null)
    11. else
    12. "b -> '$value'"
    13. }
    14. }

    现在有一个生成四次“Hello”字符串的 a 通道, 和一个生成四次“World”字符串的 通道,我们在这两个通道上使用它:

    这段代码的结果非常有趣,所以我们会在更多细节中分析它:

    1. a -> 'Hello 0'
    2. a -> 'Hello 1'
    3. b -> 'World 0'
    4. a -> 'Hello 2'
    5. a -> 'Hello 3'
    6. b -> 'World 1'
    7. Channel 'a' is closed
    8. Channel 'a' is closed

    有几个结果可以通过观察得出。

    首先,select 偏向于 第一个子句,当可以同时选到多个子句时, 第一个子句将被选中。在这里,两个通道都在不断地生成字符串,因此 a 通道作为 select 中的第一个子句获胜。然而因为我们使用的是无缓冲通道,所以 a 在其调用 时会不时地被挂起,进而 b 也有机会发送。

    第二个观察结果是,当通道已经关闭时, 会立即选择 onReceiveOrNull

    Select 表达式具有 子句,可以很好的与选择的偏向特性结合使用。

    我们来编写一个整数生成器的示例,当主通道上的消费者无法跟上它时,它会将值发送到 side 通道上:

    1. fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
    2. for (num in 1..10) { // 生产从 1 到 10 的 10 个数值
    3. delay(100) // 延迟 100 毫秒
    4. select<Unit> {
    5. onSend(num) {} // 发送到主通道
    6. side.onSend(num) {} // 或者发送到 side 通道
    7. }
    8. }
    9. }

    消费者将会非常缓慢,每个数值处理需要 250 毫秒:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.channels.*
    3. import kotlinx.coroutines.selects.*
    4. fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
    5. for (num in 1..10) { // 生产从 1 到 10 的 10 个数值
    6. delay(100) // 延迟 100 毫秒
    7. select<Unit> {
    8. onSend(num) {} // 发送到主通道
    9. side.onSend(num) {} // 或者发送到 side 通道
    10. }
    11. }
    12. }
    13. fun main() = runBlocking<Unit> {
    14. //sampleStart
    15. val side = Channel<Int>() // 分配 side 通道
    16. launch { // 对于 side 通道来说,这是一个很快的消费者
    17. side.consumeEach { println("Side channel has $it") }
    18. }
    19. produceNumbers(side).consumeEach {
    20. println("Consuming $it")
    21. delay(250) // 不要着急,让我们正确消化消耗被发送来的数字
    22. }
    23. println("Done consuming")
    24. coroutineContext.cancelChildren()
    25. //sampleEnd
    26. }

    让我们看看会发生什么:

    1. Consuming 1
    2. Side channel has 2
    3. Side channel has 3
    4. Consuming 4
    5. Side channel has 5
    6. Side channel has 6
    7. Consuming 7
    8. Side channel has 8
    9. Side channel has 9
    10. Consuming 10
    11. Done consuming

    延迟值可以使用 onAwait 子句查询。 让我们启动一个异步函数,它在随机的延迟后会延迟返回字符串:

    1. fun CoroutineScope.asyncString(time: Int) = async {
    2. delay(time.toLong())
    3. "Waited for $time ms"
    4. }

    让我们随机启动十余个异步函数,每个都延迟随机的时间。

    现在 main 函数在等待第一个函数完成,并统计仍处于激活状态的延迟值的数量。注意,我们在这里使用 select 表达式事实上是作为一种 Kotlin DSL, 所以我们可以用任意代码为它提供子句。在这种情况下,我们遍历一个延迟值的队列,并为每个延迟值提供 onAwait 子句的调用。

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.selects.*
    3. import java.util.*
    4. fun CoroutineScope.asyncString(time: Int) = async {
    5. delay(time.toLong())
    6. "Waited for $time ms"
    7. }
    8. fun CoroutineScope.asyncStringsList(): List<Deferred<String>> {
    9. val random = Random(3)
    10. return List(12) { asyncString(random.nextInt(1000)) }
    11. }
    12. fun main() = runBlocking<Unit> {
    13. //sampleStart
    14. val list = asyncStringsList()
    15. val result = select<String> {
    16. "Deferred $index produced answer '$answer'"
    17. }
    18. }
    19. }
    20. println(result)
    21. val countActive = list.count { it.isActive }
    22. println("$countActive coroutines are still active")
    23. //sampleEnd
    24. }

    该输出如下:

    1. Deferred 4 produced answer 'Waited for 128 ms'
    2. 11 coroutines are still active

    我们现在来编写一个通道生产者函数,它消费一个产生延迟字符串的通道,并等待每个接收的延迟值,但它只在下一个延迟值到达或者通道关闭之前处于运行状态。此示例将 和 onAwait 子句放在同一个 select 中:

    1. fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> {
    2. var current = input.receive() // 从第一个接收到的延迟值开始
    3. while (isActive) { // 循环直到被取消或关闭
    4. val next = select<Deferred<String>?> { // 从这个 select 中返回下一个延迟值或 null
    5. input.onReceiveOrNull { update ->
    6. update // 替换下一个要等待的值
    7. }
    8. current.onAwait { value ->
    9. send(value) // 发送当前延迟生成的值
    10. input.receiveOrNull() // 然后使用从输入通道得到的下一个延迟值
    11. }
    12. }
    13. if (next == null) {
    14. println("Channel was closed")
    15. break // 跳出循环
    16. } else {
    17. current = next
    18. }
    19. }
    20. }

    为了测试它,我们将用一个简单的异步函数,它在特定的延迟后返回特定的字符串:

    1. fun CoroutineScope.asyncString(str: String, time: Long) = async {
    2. delay(time)
    3. str
    4. }

    main 函数只是启动一个协程来打印 switchMapDeferreds 的结果并向它发送一些测试数据:

    1. import kotlinx.coroutines.*
    2. import kotlinx.coroutines.channels.*
    3. import kotlinx.coroutines.selects.*
    4. fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> {
    5. var current = input.receive() // 从第一个接收到的延迟值开始
    6. while (isActive) { // 循环直到被取消或关闭
    7. val next = select<Deferred<String>?> { // 从这个 select 中返回下一个延迟值或 null
    8. input.onReceiveOrNull { update ->
    9. update // 替换下一个要等待的值
    10. }
    11. current.onAwait { value ->
    12. send(value) // 发送当前延迟生成的值
    13. input.receiveOrNull() // 然后使用从输入通道得到的下一个延迟值
    14. }
    15. }
    16. if (next == null) {
    17. println("Channel was closed")
    18. break // 跳出循环
    19. } else {
    20. current = next
    21. }
    22. }
    23. }
    24. fun CoroutineScope.asyncString(str: String, time: Long) = async {
    25. delay(time)
    26. str
    27. }
    28. fun main() = runBlocking<Unit> {
    29. //sampleStart
    30. val chan = Channel<Deferred<String>>() // 测试使用的通道
    31. launch { // 启动打印协程
    32. for (s in switchMapDeferreds(chan))
    33. println(s) // 打印每个获得的字符串
    34. }
    35. chan.send(asyncString("BEGIN", 100))
    36. delay(200) // 充足的时间来生产 "BEGIN"
    37. chan.send(asyncString("Slow", 500))
    38. delay(100) // 不充足的时间来生产 "Slow"
    39. chan.send(asyncString("Replace", 100))
    40. delay(500) // 在最后一个前给它一点时间
    41. chan.send(asyncString("END", 500))
    42. delay(1000) // 给执行一段时间
    43. chan.close() // 关闭通道……
    44. delay(500) // 然后等待一段时间来让它结束

    这段代码的执行结果: