为什么onEach不能在Android版的Kotlin Flow中工作



在Fragment中,我称一个视图模型很有趣,我在其中编写了这段代码,但它没有打印任何内容!仅";你好,叫"正在打印。

代码:

fun fetchUserReviewData1() {
LogUtils.d("Hello called")
flow {
(1..5).forEach {
LogUtils.d("Hello UserReviewViewModel1 it: " + it)
//        delay(100) //delay the emission
emit(it)
}
}.onEach { LogUtils.d("Hello UserReviewViewModel it: " + it) }
}

它不工作的原因是默认情况下Flow是冷的。这意味着flow { ... }指令和下面的onEach { ... }指令中的代码在调用collect之前不会执行

最新更新