Search code examples
androidandroid-roomandroid-livedatakotlin-flow

Does Kotlin Flow Emits new data every time if something changed in room database?


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?


Solution

  • Yes Flow emits new data if anything changes in the room database, 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 emitted data without live changes:

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

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