I have two DAOs, two Repositories and two POJOs. There is some way to create one Livedata of two? I need it to make single list for Recyclerview. POJOs are similar objects.<
I assume you want to combine them, yes? You'll need a MediatorLiveData, but the guy saying you now need Object is wrong. What you need is a MediatorLiveData
.
public class CombinedLiveData extends MediatorLiveData, List>> {
private List expenses = Collections.emptyList();
private List incomes = Collections.emptyList();
public CombinedLiveData(LiveData> ld1, LiveData> ld2) {
setValue(Pair.create(expenses, incomes));
addSource(ld1, expenses -> {
if(expenses != null) {
this.expenses = expenses;
}
setValue(Pair.create(expenses, incomes));
});
addSource(ld2, incomes -> {
if(incomes != null) {
this.incomes = incomes;
}
setValue(Pair.create(expenses, incomes));
});
}
}
You could potentially make this generic and it'd be the implementation of combineLatest
for two LiveData using tuples of 2-arity (Pair).
EDIT: like this:
public class CombinedLiveData2 extends MediatorLiveData> {
private A a;
private B b;
public CombinedLiveData2(LiveData ld1, LiveData ld2) {
setValue(Pair.create(a, b));
addSource(ld1, a -> {
if(a != null) {
this.a = a;
}
setValue(Pair.create(a, b));
});
addSource(ld2, b -> {
if(b != null) {
this.b = b;
}
setValue(Pair.create(a, b));
});
}
}
Beware that I lost the ability to set Collections.emptyList()
as initial values of A
and B
with this scenario, and you WILL need to check for null
s when you access the data inside the pair.
EDIT: You can use the library https://github.com/Zhuinden/livedata-combinetuple-kt which does the same thing.