Android room & Many2many relations

Many Android programmers use Room and live data libraries. All things are good, but Room is not orm!

Room generates convertation code from SQL to objects, but it doesn’t work with relation in all cases. Example from real life: I develop aircraft guide, so one aircraft could have several countries, which develop it. In this case, we must use a many2many link.

So, entities may look like this:

We can’t get countries for specified aircraft through @Relation for getting live data. So, we need composing several live data into one. Get MediatorLiveData from a google library and create a merger based on Observer:

How it works: data from DB loads parallel to separate live data. We set it to the mediator and for each set observer. Observer works when all data is received. For correct concurrent works, it uses AtomicInteger counter. Usage may look like this: