kotlin コルーチン ブロードキャスト パイプライン BroadcastChannel、サブスクリプション パイプライン openSubscription
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main(args: Array<String>) {
//广播消息
//也可以把普通Channel转换成广播Channel
//val channel = Channel<Int>()
//val broadcast = channel.broadcast(5)
val broadcastChannel = BroadcastChannel<Int>(5)
CoroutineScope(Dispatchers.IO).launch {
var i = 0
while (true) {
broadcastChannel.send(i)
i++
delay(1000)
}
}
//订阅消息
val receiveChannel1 = broadcastChannel.openSubscription()
val receiveChannel2 = broadcastChannel.openSubscription()
runBlocking {
while (true) {
var v1 = receiveChannel1.receive()
println("rc1 - $v1")
var v2 = receiveChannel2.receive()
println("rc2 - $v2")
}
}
}