Home > Enterprise >  Why doest onEach is not working in Kotlin Flow for Android?
Why doest onEach is not working in Kotlin Flow for Android?

Time:08-30

From Fragment, I'm calling one viewmodel fun and inside that I written this piece of code, but it's not printing anything! Only "Hello called" is printing.

Code:

 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) }

}

CodePudding user response:

The reason it's not working is that by default a Flow is cold. It means the code inside your flow { ... } directive and the following onEach { ... } won't be executed until a collect is called on it.

  • Related