美文网首页
Kotlin中Flow 冷流热流

Kotlin中Flow 冷流热流

作者: 雨来 | 来源:发表于2021-06-16 18:18 被阅读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)
    }
}

相关文章

网友评论

      本文标题:Kotlin中Flow 冷流热流

      本文链接:https://www.haomeiwen.com/subject/aajfyltx.html