0
0
Android Kotlinmobile~7 mins

Room with Flow for reactive data in Android Kotlin

Choose your learning style9 modes available
Introduction

Room with Flow helps your app watch database changes and update the screen automatically. It makes your app feel fast and fresh without manual refresh.

You want to show a list of items that updates when data changes.
You want to keep the UI in sync with the database without extra code.
You want to react to data changes in real-time, like chat messages or tasks.
You want to avoid manual refresh buttons and keep data fresh automatically.
Syntax
Android Kotlin
import kotlinx.coroutines.flow.Flow

@Dao
interface MyDao {
  @Query("SELECT * FROM my_table")
  fun getAllItems(): Flow<List<MyEntity>>
}

The function returns a Flow that emits data updates automatically.

Use Flow with Kotlin coroutines for reactive streams of data.

Examples
This returns a flow of user lists that updates when the users table changes.
Android Kotlin
@Dao
interface UserDao {
  @Query("SELECT * FROM users")
  fun getUsers(): Flow<List<User>>
}
This returns only tasks not done, updating automatically when tasks change.
Android Kotlin
@Dao
interface TaskDao {
  @Query("SELECT * FROM tasks WHERE done = 0")
  fun getPendingTasks(): Flow<List<Task>>
}
Sample App

This example shows a Room entity Note and a DAO returning a Flow of all notes. The ViewModel collects this flow and updates a state flow to keep UI reactive.

Android Kotlin
import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Entity(tableName = "notes")
data class Note(
  @PrimaryKey(autoGenerate = true) val id: Int = 0,
  val content: String
)

@Dao
interface NoteDao {
  @Query("SELECT * FROM notes")
  fun getAllNotes(): Flow<List<Note>>

  @Insert
  suspend fun insert(note: Note)
}

@Database(entities = [Note::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
  abstract fun noteDao(): NoteDao
}

// Usage in a ViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class NoteViewModel(private val dao: NoteDao) : ViewModel() {
  private val _notes = MutableStateFlow<List<Note>>(emptyList())
  val notes: StateFlow<List<Note>> = _notes

  init {
    viewModelScope.launch {
      dao.getAllNotes().collectLatest { list ->
        _notes.value = list
      }
    }
  }
}
OutputSuccess
Important Notes

Remember to collect the Flow in a coroutine scope, like ViewModelScope, to get updates.

Room automatically emits new data when the database changes, no extra code needed.

Use StateFlow or LiveData in your UI layer to observe the Flow.

Summary

Room with Flow lets your app react to database changes automatically.

Use Flow in DAO queries to get reactive streams of data.

Collect the Flow in a coroutine scope to update your UI smoothly.