bennyhuo / Bennyhuo

bennyhuo.vercel.app
8 stars 3 forks source link

破解 Kotlin 协程(9) - Channel 篇 | Bennyhuo #24

Open bennyhuo opened 5 years ago

bennyhuo commented 5 years ago

https://www.bennyhuo.com/2019/09/16/coroutine-channel/

Channel 实际上就是协程在生产消费者模型上的应用,把过去你用 BlockingQueue 实现的功能替换成 Channel,也许会有新的发现~

GvcZhang commented 4 years ago

对这里的produer和actor的使用有点迷,为什么send数据都要放在闭包里

val receiveChannel: ReceiveChannel = GlobalScope.produce { while(true){ delay(1000) send(2) } }

我能否拿到这个channel在其他的线程里send呢,具体怎么做

bennyhuo commented 4 years ago

@GvcZhang 对这里的produer和actor的使用有点迷,为什么send数据都要放在闭包里

val receiveChannel: ReceiveChannel = GlobalScope.produce { while(true){ delay(1000) send(2) } }

我能否拿到这个channel在其他的线程里send呢,具体怎么做

是要放到协程里面,你可以在任何协程里面使用 channel 的 send