Search code examples
androidandroid-roomandroid-mvvm

MVVM/Room pulling a single item from the Dao or Repository, what is the best approach?


I want to get a single item using MVVM/Room and edit it in a detail screen. I followed a number of guides and examples for creating a MVVM/Room application. And in many of them the Repository class looks like this:

public class ScenarioRepository {

    private static final String TAG="ScenarioRepository";

    private ScenarioDao scenarioDao;
    private LiveData<List<Scenario>> allScenarios;


    public ScenarioRepository(Application application) {

        AppDatabase database = AppDatabase.getInstance(application);
        scenarioDao = database.scenarioDao();
        allScenarios = scenarioDao.getAllScenarios();
    }
    ....
}

The examples focus on filling a RecyclerView and when editing one of the records pass all values from the RecyclerView to the edit screen. Frequently there is more information in the record than appears on the RecyclerView, so I would prefer to pull the record from the database and have seen some MVVM implementations where the DAO has a specific call for an item like this:

@Query("select * from Scenario where id = :id")
Scenario getItembyId(int id);

What is the best way to retrieve the Scenario I want in this example? Why do I need to get an individual item when the full list of Scenarios is pulled by the Repository from the DOW in the constructor? Should I have a way in the repository to pull the Scenario from member variable allScenarios in the Repository as opposed to going back to the database/Room?

UPDATE I followed these instructions which covered the master/detail scenario very well. The I extended the RecyclerView like in this video which made it easy to set the item during the onItemClick event and pass it to the ViewModel so the detail fragment could get it.


Solution

  • A query for filtering by id is useful in the case that you do not need an entire list of data but just single items.

    If you observe the entire list anyways, but for certain UI components need to get an item by id, I would suggest you to filter the list for that specific item id.

    You could retrieve your object by a query like in your question, or if you want to observe for changes in the database, wrap it in a LiveData.