// 使用通道创建定时操作,和Go协程一样的.
lifecycleScope.launchWhenResumed {
// 1.创建通道
val channel = Channel<Int>()
// 2.向通道发送数据
launch(Dispatchers.IO) {
for (i in 1..100) {
delay(150) // 延时0.15秒发送
channel.send(i)
}
channel.close()
}
// 3.通道接收数据
launch(Dispatchers.IO) {
for (n in channel) {
activity?.runOnUiThread {
// n为channel.send(i)发送过来的数据
}
}
}
}
使用Kotlin协程Channel做一个定时器
最新推荐文章于 2024-08-06 19:30:00 发布