Home > Software design >  Does Kotlin Flow Emits new data every time if something changed in room database?
Does Kotlin Flow Emits new data every time if something changed in room database?

Time:06-21

Let's Say Here is Sample Code

LiveData Query

Query("SELECT IFNULL(COUNT(id),0) FROM Item WHERE status = :status")
fun getLiveData(status: Int): LiveData<Int>

Kotlin Flow Query

@Query("SELECT IFNULL(COUNT(id),0) FROM Item WHERE status = :status")
fun getFlowData(status: Int): Flow<Int>

So my Question is Flow gets new data if anything changes in the room database?

CodePudding user response:

Yes Flow gets new data if anything changes in the room database if you collect that flow of course, like the example below:

val flow = getFlowData(2) // type Flow<Int>
flow.collect { data ->
    // every time anything changes, the code inside collect is going to get called again
}

and also there is .first() that will give you only the latest data without live changes:

val data = getFlowData(2).first() // type Int

So it depends how you use Flow, and it depends on your needs.

  • Related