Kotlin中Flow 冷流热流

2021-06-16  本文已影响0人  雨来

flow中的冷流和热流 (同步非阻塞 和异步非阻塞)

1、通过 flow{ ... } 返回的就是 冷流 同时是 同步的
2、通过 channelFlow 返回的是 热流 是异步的
3、同步的比异步的话费时间
4、flow{ ... } 可以通过 flowOn切换线程 切换成子线程后和 channelFlow花的时间差不多

代码

fun main() = runBlocking {
    val time = measureTimeMillis {
//        equeneFlow() //同步 1秒左右
        asyncFlow() //异步700多毫秒


    }
    print("cost $time")

}

private suspend fun asyncFlow() {
    channelFlow {
        for (i in 1..5) {
            delay(100)
            send(i)
        }
    }.collect {
        delay(100)
        println(it)
    }
}

//同步的
private suspend fun equeneFlow() {
    flow<Int> {
        for (i in 1..5) {
            delay(100)
            emit(i)
        }
    }.collect {

        delay(100)
        println(it)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读