一、前言
select 表达式可以同时等待多个挂起函数,并 选择 第一个可用的。这样就可以实现这样一种功能,同时执行不同的处理,哪种返回了就处理哪种。
二、select
下面是一种简单的演示:
fun CoroutineScope.fizz() = produce<String> {
while (true) {
delay(300)
send("Fizz")
}
}
fun CoroutineScope.buzz() = produce<String> {
while (true) {
delay(500)
send("Buzz!")
}
}
suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
select<Unit> {
fizz.onReceive { value ->
println("fizz -> '$value'")
}
buzz.onReceive { value ->
println("buzz -> '$value'")
}
}
}
@Test
fun test() = runBlocking<Unit> {
val fizz = fizz()
val buzz = buzz()
repeat(7) {
selectFizzBuzz(fizz, buzz)
}
coroutineContext.cancelChildren()
}
可以发现运行结果如下:
fizz -> 'Fizz'
buzz -> 'Buzz!'
fizz -> 'Fizz'
fizz -> 'Fizz'
buzz -> 'Buzz!'
fizz -> 'Fizz'
buzz -> 'Buzz!'
三、通道关闭时候的Select
select 中的 onReceive 子句在已经关闭的通道执行会发生失败,并导致相应的 select 抛出异常。我们可以使用 onReceiveOrNull 子句在关闭通道时执行特定操作。以下示例还显示了 select 是一个返回其查询方法结果的表达式:
suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
select<String> {
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'"
}
}
fun main() = runBlocking<Unit> {
val a = produce<String> {
repeat(4) { send("Hello $it") }
}
val b = produce<String> {
repeat(4) { send("World $it") }
}
repeat(8) {
println(selectAorB(a, b))
}
coroutineContext.cancelChildren()
}
注意,onReceiveOrNull 是一个仅在用于不可空元素的通道上定义的扩展函数,以使关闭的通道与空值之间不会出现意外的混乱。
结果如下:
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 偏向于 第一个子句,当可以同时选到多个子句时, 第一个子句将被选中。在这里,两个通道都在不断地生成字符串,因此 a 通道作为 select 中的第一个子句获胜。然而因为我们使用的是无缓冲通道,所以 a 在其调用 send 时会不时地被挂起,进而 b 也有机会发送。
第二个观察结果是,当通道已经关闭时, 会立即选择 onReceiveOrNull。
四、onSend
Select 表达式具有 onSend 子句,可以很好的与选择的偏向特性结合使用。
fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
for (num in 1..10) {
delay(100)
select<Unit> {
onSend(num) {}
side.onSend(num) {}
}
}
}
fun main() = runBlocking<Unit> {
val side = Channel<Int>()
launch {
side.consumeEach { println("Side channel has $it") }
}
produceNumbers(side).consumeEach {
println("Consuming $it")
delay(250)
}
println("Done consuming")
coroutineContext.cancelChildren()
}
运行结果如下
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
延迟值可以使用 onAwait 子句查询。 让我们启动一个异步函数,它在随机的延迟后会延迟返回字符串:
fun CoroutineScope.asyncString(time: Int) = async {
delay(time.toLong())
"Waited for $time ms"
}
fun CoroutineScope.asyncStringsList(): List<Deferred<String>> {
val random = Random(3)
return List(12) { asyncString(random.nextInt(1000)) }
}
fun main() = runBlocking<Unit> {
val list = asyncStringsList()
val result = select<String> {
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")
}
其运行结果如下:
Deferred 4 produced answer 'Waited for 128 ms'
11 coroutines are still active
六、在延迟通道上切换
这一段看不懂
我们现在来编写一个通道生产者函数,它消费一个产生延迟字符串的通道,并等待每个接收的延迟值,但它只在下一个延迟值到达或者通道关闭之前处于运行状态。此示例将 onReceiveOrNull 和 onAwait 子句放在同一个 select 中:
fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> {
var current = input.receive()
while (isActive) {
val next = select<Deferred<String>?> {
input.onReceiveOrNull { update ->
update
}
current.onAwait { value ->
send(value)
input.receiveOrNull()
}
}
if (next == null) {
println("Channel was closed")
break
} else {
current = next
}
}
}
fun CoroutineScope.asyncString(str: String, time: Long) = async {
delay(time)
str
}
fun main() = runBlocking<Unit> {
val chan = Channel<Deferred<String>>()
launch {
for (s in switchMapDeferreds(chan))
println(s)
}
chan.send(asyncString("BEGIN", 100))
delay(200)
chan.send(asyncString("Slow", 500))
delay(100)
chan.send(asyncString("Replace", 100))
delay(500)
chan.send(asyncString("END", 500))
delay(1000)
chan.close()
delay(500)
}
结果如下:
BEGIN
Replace
END
Channel was closed
七、参考链接
-
select 表达式(实验性的) https://www.kotlincn.net/docs/reference/coroutines/select-expression.html
|