0

I have my DAO set up as follows:

public interface AllocationDao {
    @Query("SELECT * from allocation")
    LiveData<List<Allocation>> getAllocations();

    @Query("SELECT * from allocation where id = :id")
    Allocation getAllocationForId(int id);

    @Query("SELECT * from lineitem where allocation_id = :id")
    List<LineItem> getLineItemsForId(int id);

    @Insert
    void insertAll(Allocation... allocations);

    @Insert
    void insertAll(LineItem... lineItems);
}

Is it possible to trigger the observer for getAllocations() when I do an insertAll(LineItem... lineItems)? What is happening now is when I do an insert to LineItem, I need the Allocation query to run, but since the query is unmodified, it's not running.

Jason John
  • 934
  • 2
  • 12
  • 23

1 Answers1

1

You could use MediatorLiveData

Firstly, add a method to your dao which observes lineItems

@Query("SELECT * FROM lineItem")
LiveData<List<Allocation>>  observeLineItems();

Secondly use MediatorLiveData to observe both the LineItems and Allocations

val mediatorLiveData = MediatorLiveData<R>()
mediatorLiveData.addSource(observeLineItems()){
   // extract this to a single function that will be called each time either source changes
}
mediatorLiveData.addSource(getAllocations()){
   // extract this to a single function that will be called each time either source changes
}

Note: I've not tested this out so it may not be syntactically perfect. This answer has a nice extension function which makes the above cleaner

Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34