使用Kotlin协程Channel做一个定时器

// 使用通道创建定时操作,和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)发送过来的数据
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/MoLiao2046/article/details/110426900
今日推荐