Kotlin Flow与ChannelFlow

通过Kotlin的Flow可以轻松实现生产者消费者模型。Flow默认是Cold的,生产者和消费者的通信是同步非阻塞的,也就是生产和消费会顺序交替进行

suspend fun productor() = flow<Int> {
        for (i in 1..10) {
            delay(100)
            emit(i)
            println("produce $i")
        }
    }

fun main {
    runBlcking {
        productor().collect {
            delay(100)
            println("custom $it")
        }           
    }
}

完成全部过程大约需要2s,因为生产者消费者按照下面顺序进行

如果,我们希望生产者消费者两端能够实现异步非阻塞模型呢?此时可以使ChannelFlow,顾名思义ChannelFlow兼容了Coroutine Channel和Flow的优点:

suspend fun productor() = channelFlow<Int> {
        for (i in 1..10) {
            delay(100)
            send(i) //emit 变为 send
            println("produce $i")
        }
    }

此时,完成整个过程只需要1s左右,生产和消费两端实现了并行执行,当消费者需要等待生产者时,也不会像Channel那样阻塞线程

发布了11 篇原创文章 · 获赞 1 · 访问量 249

猜你喜欢

转载自blog.csdn.net/vitaviva/article/details/104105970