Mapping Data to… LiveData?

So now we have a list of Customer IDs. Suppose that we now want to retrieve the categories associated with all of the Customer entities. That requires another database request via our DAO:

@Query("SELECT categories.* FROM categories\n"+
  "INNER JOIN customer_category_join ON categories.id=customer_category_join.categoryId\n"+
  "WHERE customer_category_join.customerId IN (:customerIds)")
LiveData<List<Category>> categoriesForCustomers(List<String> customerIds);

And if we are on the main application thread — as is typical when working with LiveData results — we need the DAO to return another LiveData.

In principle, you could use map() for this. However, for this scenario, there is switchMap(). This says that the objects being created via the mapping are themselves LiveData. This helps the LiveData system keep everything in sync, particularly across lifecycle events.

So, given the liveCustomerIds from the preceding section, we can get the categories via:

final LiveData<List<Category>> liveCategories=
  Transformations.switchMap(liveCustomerIds,
    new Function<List<String>, LiveData<List<Category>>>() {
      @Override
      public LiveData<List<Category>> apply(List<String> customerIds) {
        return(store.categoriesForCustomers(customerIds));
      }
    });

And, if we arrange to observe() that liveCategories object, we will be called with onChanged() when the list of Category objects is available, after the initial database I/O to get the customers, then the secondary database I/O to get the categories for those customers.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.