Skip to content
Advertisement

Merging multiple LiveData sources?

To make it easier to visualize my problem I drew the following: enter image description here

I am using a RoomDatabase, a Repository, a Viewmodel and Livedata. Areas have a 1 to n relationship with Gateways and Gateways a 1 to n relationship with Items. I created both an AreaWithGateways entity and a GatewayWithItems entity.

Items can move from a gateway to another, which is why I observe them with Livedata to keep track of which Gateway they’re in. My problem now is that I found myself in need to also keep track of which Items are in which Areas and I can’t figure out how to do that.

I’ve thought of merging the LiveData of each Gateway together and observing that using MediatorLiveData but I didn’t really understand how to use it. Or maybe it’s possible to create an Entity AreaWithGatewayswithItems?

Any insight would be appreciated

Edit: I am adding some code to make the problem a bit clearer

This is the Area Entity

JavaScript

The Gateway Entity:

JavaScript

And the “Item” Entity:

JavaScript

And this is the relation “AreaWithGateways”:

JavaScript

As well as GatewaysWithCows:

JavaScript

I’ve been trying to find a way of getting all of the “items” in an Area as Livedata but still can’t figure it out. I feel like I should somehow use AreaWithGateways to add the LiveData items together but I can’t reach the items through the gateways, it has to be the other way around.

Advertisement

Answer

Or maybe it’s possible to create an Entity AreaWithGatewayswithItems?

Not an Entity as these are used to define tables BUT via POJO’s using @Embedded and @Relation annotation (e.g. your GatewayWithCows is a POJO).

I feel like I should somehow use AreaWithGateways to add the LiveData items together but I can’t reach the items through the gateways, it has to be the other way around.

You basically use a hierarchical approach but POJO’s so as you have GatewayWithCows then relate to this from Area as per :-

JavaScript
  • Note I missed the s after Gateway for the class name (and as such in the query below)

  • Note the use of entity = Gateway.class is required as the relationship is via the Gateway NOT via the GatewayWithCows (which isn’t a table).

The Query Dao could be as simple as :-

JavaScript
  • amended accordingly for LiveData.
  • note that if you use JOINS in the query then the any clauses such as WHERE will only affect the Area’s, not the underlying Gateways and Cows. That is irrespective of the query @Relation builds each Area with ALL Gateways related to that Area; and each Gateway gets ALL the Cows related to that Gateway.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement