【KTips】把 Flow 变成 Iterator

45 阅读1分钟

欢迎来到一分钟 KT Tips! 🎉

 

想必在日常生活中,大家总会遇到这样的苦恼:

我想要把一个 Flow 转化为 Iterator 怎么办呢?

fun main() {
    val flow = flowOf(1, 2, 3)
    
    // val iter: Iterator<Int> = ?
}

也许你可以试试用 Flow.produceIn

val myScope = CoroutineScope(Dispatchers.IO)

fun main() {
    val flow = flowOf(1, 2, 3)

    val channelIter: ChannelIterator<Int> = flow.produceIn(myScope).iterator()

    val iter: Iterator<Int> = iterator {
        while (runBlocking { channelIter.hasNext() }) {
            yield(channelIter.next())
        }
    }
}

如果条件合适,也可以选择使用 GlobalScope:

fun main() {
    val flow = flowOf(1, 2, 3)

    val channelIter: ChannelIterator<Int> = flow.produceIn(GlobalScope).iterator()

    val iter: Iterator<Int> = iterator {
        while (runBlocking { channelIter.hasNext() }) {
            yield(channelIter.next())
        }
    }
}

你学会了吗?

如果有其他好观点和补充也欢迎评论区补充喔~我们下次再见 ヾ(•ω•`)o