Here is an example of what I have to work with, I have two repositories one for homes and another for cars. The homes repository wraps a local sqlite db with a few tables. The cars repository is similar and has it's own sqlite db with different tables.
Homes DB
House Table
-----------
int id
string owner_first_name
int sqft
int floors
int car_id
Cars DB
Car Table
----------
int id
string make
string model
string nickname
int year
I'm trying to make two livedata functions in the house repository. One for returning an individual house and associated car nickname and another for returning a list of houses with the associated car nickname. I can add new methods to the car repository but I can't combine these repositories or databases, right now the only useful method from the car repository available is a getCarLive(car_id: int) : LiveData<Car>
function.
I tried to use a map, call getCarLive()
, and observe the result but the map returns before the observer is called so the carNick is never set.
getHouseLive(houseId: int) =
houseDao.getHouseLive(houseId).map {
val house_car_obj = HouseCar(it.id, it.sqft, it.owner_first_name)
val observer = Observer<Car?> { c ->
if (c != null) { house_car_obj.carNick = c.nickname }
}
val carLiveData = carRepository.getCarLive(it.car_id)
carLiveData.observeForever(observer)
}
house_car_obj
}
I'm not sure what to try next, One thought was to return a nested LiveData, so I would structure the HouseCar
like this
data class HouseCar(val id: int, val sqft: Int, val ownerName: String, val car: LiveData<car>)
Another thought I had was to make a non live data version of suspend fun getCar()
in the car repository but then I need figure out how to call that from a background thread.
I tried searching but I only was able to find examples which combined different lists of objects into one list using MediatorLiveData. For example this question on SO. The other problem with using MediatorLiveData is that I need the result of the first call to get the car_id
before I can actually make the call to the second repository so I didn't know how to set that up with MediatorLiveData either.