Ishika Singh
Ishika Singh

Reputation: 163

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

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

}

Upvotes: 0

Views: 1725

Answers (1)

Antoine
Antoine

Reputation: 305

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.

Upvotes: 3

Related Questions