Search code examples
androidandroid-roomandroid-livedataandroid-architecture-componentsandroid-viewmodel

What is the correct usage of Flow in Room?


I am using Room and I have written the Dao class as follows.

Dao

@Dao
interface ProjectDao {
    @Query("SELECT * FROM project")
    fun getAllProjects(): Flow<List<Project>>

    ...etc
}

and this Flow is converted to LiveData through asLiveData() in ViewModel and used as follows.

ViewModel

@HiltViewModel
class MainViewModel @Inject constructor(
    private val projectRepo: ProjectRepository
) : ViewModel() {
    val allProjects = projectRepo.allProjects.asLiveData()
    ...
}

Activity

mainViewModel.allProjects.observe(this) { projects ->
    adapter.submitList(projects)
    ...
}

When data change occurs, RecyclerView is automatically updated by the Observer. This is a normal example I know.

However, in my project data in Flow, what is the most correct way to get the data of the position selected from the list? I have already written code that returns a value from data that has been converted to LiveData, but I think there may be better code than this solution.

private fun getProject(position: Int): Project {
    return mainViewModel.allProjects.value[position]
}

Please give me suggestion


Solution

  • Room has in built support of flow.

    @Dao
    interface ProjectDao {
        @Query("SELECT * FROM project")
        fun getAllProjects(): Flow<List<Project>>
    
        //lets say you are saving the project from any place one by one.
        @Insert()
        fun saveProject(project :Project)
    }
    

    if you call saveProject(project) from any place, your ui will be updated automatically. you don't have to make any unnecessary call to update your ui. the moment there is any change in project list, flow will update the ui with new dataset.

    to get the data of particular position, you can get it from adapter list. no need to make a room call.