Room How to get 2 entities as 1 live data list?

Viewed 66

I want to get 2 different entities as 1 LiveData List so that I could show them in a RecyclerView and update it on data changes

1 Answers

If I understand correctly, you have 2 room entities, both with one value, in it's own dao. You want to combine those to a list (with up to 2 items) that can be observed as liveData.

I would go with a MediatorLiveData, get the entities as liveData from Room, and combine them like this:

class SomeClass {
    private val list1: LiveData<Something> = dao1.getLiveSomething()
    private val list2: LiveData<Something> = dao2.getOtherLiveSomething()
    private val _combinedList = MediatorLiveData<List<Something>>().apply{
        addSource(list1){
            value = listOfNotNull(it, list2.value)
        }
        addSource(list2){
            value = listOfNotNull(list1.value, it)
        }
    }

    /**
     * Observe this for combined list
     */
    val combinedList: LiveData<List<Something>>
        get() = _combinedList
}

This way, when one of the entities in Room get changed, combinedList will send the new data to any observers.

Related