文章目录
- 一、BroadcastChannel 广播通道
- 二、代码示例
一、BroadcastChannel 广播通道
在之前的博客中 介绍的 Channel 通道 的 数据发送协程 ( 生产者 ) 和 数据接收协程 ( 消费者 ) 数据接收 都是一对一的 ,
生产者 发送一个数据 , 消费者 只能接收一个数据 ,
如果有 多个 消费者协程 , 这个 数据谁抢到就算谁的 , 其它消费者无法再次获取相同的数据 ,
多个 消费者协程 之间接收的数据 , 存在互斥 ;
BroadcastChannel 广播通道 发出的数据 , 可以同时被多个 消费者协程 接收 , 互相之间不存在互斥行为 ;
二、代码示例
代码示例 : 在 生产者协程 中 , 通过 BroadcastChannel 发送数据 , 启动 3 个 消费者协程 , 同时接收 BroadcastChannel 的数据 , 3 个协程中都可以获取完整的数据 ;
package kim.hsl.coroutineimport android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channelclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)runBlocking {// BroadcastChannel 广播通道, 传递 Int 类型数据val broadCastChannel = BroadcastChannel<Int>(Channel.BUFFERED)// 数据生产者协程val producer = GlobalScope.launch {for (i in 0..2) {delay(100)broadCastChannel.send(i)println("向通道中发送数据 $i")}// 关闭通道broadCastChannel.close()}List(3) { index ->// 数据消费者协程GlobalScope.launch {val channel = broadCastChannel.openSubscription()for (num in channel) {delay(1000)println("消费者协程 $index 从通道中接收数据 $num")}}}.joinAll()}}
}
执行结果 :
2022-12-28 11:33:45.343 I/System.out: 向通道中发送数据 0
2022-12-28 11:33:45.482 I/System.out: 向通道中发送数据 1
2022-12-28 11:33:45.623 I/System.out: 向通道中发送数据 2
2022-12-28 11:33:46.385 I/System.out: 消费者协程 0 从通道中接收数据 0
2022-12-28 11:33:46.388 I/System.out: 消费者协程 2 从通道中接收数据 0
2022-12-28 11:33:46.388 I/System.out: 消费者协程 1 从通道中接收数据 0
2022-12-28 11:33:47.389 I/System.out: 消费者协程 0 从通道中接收数据 1
2022-12-28 11:33:47.390 I/System.out: 消费者协程 2 从通道中接收数据 1
2022-12-28 11:33:47.391 I/System.out: 消费者协程 1 从通道中接收数据 1
2022-12-28 11:33:48.393 I/System.out: 消费者协程 0 从通道中接收数据 2
2022-12-28 11:33:48.393 I/System.out: 消费者协程 2 从通道中接收数据 2
2022-12-28 11:33:48.394 I/System.out: 消费者协程 1 从通道中接收数据 2