1

I'm getting a LiveData> from a database in my view model. But I have to add some Foo-objects to the list, before I can forward them to the view.

I'm using the Room API to get access to a database. I'm using the recommended encapsulation with a Dao, a repository and the view model. The repository just forwards the LiveData from the Dao. In the view model, I call the method from the repository and store the result in a variable. Because I can't use the observe-method of the LiveData-object, I tried it with the Transformations.map-method. But the map-method isn't called at any time.

public class FooViewModel extends AndroidViewModel {
   private LiveData<List<Foo>> fromDatabase;
   private MutableLiveData<List<Foo>> forView;

   public FooViewModel(/*...*/) {
      //...
      forView = new MutableLiveData<>();
   }

   //Returns the LiveData<List> for the view, that should be observed
   public LiveData<List<Foo>> getViewList() {
      return forView;
   }

   //Loads the data from the database, modifies it and maps it to the LiveData for the view
   public void loadFromDatabase(/*Some conditions for query*/) {
      fromDatabase = repository.getData(/*Some conditions*/);
      Transformations.map(fromDatabase, (foos) -> {
         forView.setValue(fillList(foos));
         return forView;
      }
   }

   //Fills the list with some other foos
   private static List<Foo> fillList(List<Foo> foos) {
      //Fill the list
   }
}

And in the view I observe the list in a way like this:

public class FooActivity {
   protected void onCreate(/*Some inputs*/) {
      viewModel.getViewList().observe(this, (foos) -> /*Display the list*/);
      viewModel.loadFromDatabase(/*with some conditions*/);
   }
}

And then nothing happens... I tried also to forward the LiveData got from the repository and observe it. That observation works fine. But not the modified one.

Naryxus
  • 55
  • 1
  • 6
  • You need to do the exact same thing I did here: https://stackoverflow.com/a/53999441/2413303 except instead of `filter` you need to build a list of your items – EpicPandaForce Jan 03 '19 at 22:13

1 Answers1

1
   //Loads the data from the database, modifies it and maps it to the LiveData for the view
   public void loadFromDatabase(/*Some conditions for query*/) {
      fromDatabase = repository.getData(/*Some conditions*/);
      Transformations.map(fromDatabase, (foos) -> {
         forView.setValue(fillList(foos));
         return forView;
      }
   }

This will never work. fromDatabase is replaced but the transformation is done against the previous fromDatabase instance.

You need to set the query conditions into a MutableLiveData to which you do Transformations.switchMap to return the LiveData<List<T>> with the correct filters applied through the DAO.

Then if you modify the conditions live data, the DAO will re-evaluate the new list with the new conditions.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428