【翻译】kotlin协程核心库文档(七)—— select 表达式

github原文地址

原创翻译,转载请保留或注明出处:https://www.jianshu.com/p/70b7be169fae

select 表达式


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

从 channel 查询

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

fun fizz(context: CoroutineContext) = produce(context) {
    while (true) { // sends "Fizz" every 300 ms
        delay(300)
        send("Fizz")
    }
}

接着 buzz 每500毫秒产出 “Buzz!” 字符串:

fun buzz(context: CoroutineContext) = produce(context) {
    while (true) { // sends "Buzz!" every 500 ms
        delay(500)
        send("Buzz!")
    }
}

使用 receive 挂起函数,我们可以从一个或另一个 channel 接收数据。但是 select 表达式允许我们同时使用其 onReceive 子句从两者接收:

suspend fun selectFizzBuzz(fizz: ReceiveChannel, buzz: ReceiveChannel) {
    select { //  means that this select expression does not produce any result
        fizz.onReceive { value -> // this is the first select clause
            println("fizz -> '$value'")
        }
        buzz.onReceive { value -> // this is the second select clause
            println("buzz -> '$value'")
        }
    }
}

让我们一起运行7次:

fun main(args: Array) = runBlocking {
    val fizz = fizz(coroutineContext)
    val buzz = buzz(coroutineContext)
    repeat(7) {
        selectFizzBuzz(fizz, buzz)
    }
    coroutineContext.cancelChildren() // cancel fizz & buzz coroutines
}

获取完整代码 here

这段代码的结果如下:

fizz -> 'Fizz'
buzz -> 'Buzz!'
fizz -> 'Fizz'
fizz -> 'Fizz'
buzz -> 'Buzz!'
fizz -> 'Fizz'
buzz -> 'Buzz!'

从关闭的 channel 查询

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

suspend fun selectAorB(a: ReceiveChannel, b: ReceiveChannel): String =
    select {
        a.onReceiveOrNull { value ->
            if (value == null)
                "Channel 'a' is closed"
            else
                "a -> '$value'"
        }
        b.onReceiveOrNull { value ->
            if (value == null)
                "Channel 'b' is closed"
            else
                "b -> '$value'"
        }
    }

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

fun main(args: Array) = runBlocking {
    // we are using the context of the main thread in this example for predictability ...
    val a = produce(coroutineContext) {
        repeat(4) { send("Hello $it") }
    }
    val b = produce(coroutineContext) {
        repeat(4) { send("World $it") }
    }
    repeat(8) { // print first eight results
        println(selectAorB(a, b))
    }
    coroutineContext.cancelChildren()
}

获取完整代码 here

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

a -> 'Hello 0'
a -> 'Hello 1'
b -> 'World 0'
a -> 'Hello 2'
a -> 'Hello 3'
b -> 'World 1'
Channel 'a' is closed
Channel 'a' is closed

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

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

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

Selecting to send

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

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

fun produceNumbers(context: CoroutineContext, side: SendChannel) = produce(context) {
    for (num in 1..10) { // produce 10 numbers from 1 to 10
        delay(100) // every 100 ms
        select {
            onSend(num) {} // Send to the primary channel
            side.onSend(num) {} // or to the side channel
        }
    }
}

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

fun main(args: Array) = runBlocking {
    val side = Channel() // allocate side channel
    launch(coroutineContext) { // this is a very fast consumer for the side channel
        side.consumeEach { println("Side channel has $it") }
    }
    produceNumbers(coroutineContext, side).consumeEach {
        println("Consuming $it")
        delay(250) // let us digest the consumed number properly, do not hurry
    }
    println("Done consuming")
    coroutineContext.cancelChildren()
}

获取完整代码 here

让我们看看会发生什么:

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

查询延迟值

延迟值可以使用 onAwait 子句查询。让我们启动一个延迟随机时间后返回延迟字符串的异步方法:

fun asyncString(time: Int) = async {
    delay(time.toLong())
    "Waited for $time ms"
}

让我们启动十几个,每个都延迟随机的时间。

fun asyncStringsList(): List> {
    val random = Random(3)
    return List(12) { asyncString(random.nextInt(1000)) }
}

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

fun main(args: Array) = runBlocking {
    val list = asyncStringsList()
    val result = select {
        list.withIndex().forEach { (index, deferred) ->
            deferred.onAwait { answer ->
                "Deferred $index produced answer '$answer'"
            }
        }
    }
    println(result)
    val countActive = list.count { it.isActive }
    println("$countActive coroutines are still active")
}

获取完整代码 here

输出如下:

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

切换延迟值的 channel

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

fun switchMapDeferreds(input: ReceiveChannel>) = produce {
    var current = input.receive() // start with first received deferred value
    while (isActive) { // loop while not cancelled/closed
        val next = select?> { // return next deferred value from this select or null
            input.onReceiveOrNull { update ->
                update // replaces next value to wait
            }
            current.onAwait { value ->
                send(value) // send value that current deferred has produced
                input.receiveOrNull() // and use the next deferred from the input channel
            }
        }
        if (next == null) {
            println("Channel was closed")
            break // out of loop
        } else {
            current = next
        }
    }
}

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

fun asyncString(str: String, time: Long) = async {
    delay(time)
    str
}

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

fun main(args: Array) = runBlocking {
    val chan = Channel>() // the channel for test
    launch(coroutineContext) { // launch printing coroutine
        for (s in switchMapDeferreds(chan))
            println(s) // print each received string
    }
    chan.send(asyncString("BEGIN", 100))
    delay(200) // enough time for "BEGIN" to be produced
    chan.send(asyncString("Slow", 500))
    delay(100) // not enough time to produce slow
    chan.send(asyncString("Replace", 100))
    delay(500) // give it time before the last one
    chan.send(asyncString("END", 500))
    delay(1000) // give it time to process
    chan.close() // close the channel ...
    delay(500) // and wait some time to let it finish
}

获取完整代码 here

这段代码的结果:

BEGIN
Replace
END
Channel was closed

扩展阅读


  • Guide to UI programming with coroutines

  • Guide to reactive streams with coroutines

  • Coroutines design document (KEEP)

  • Full kotlinx.coroutines API reference

你可能感兴趣的:(【翻译】kotlin协程核心库文档(七)—— select 表达式)