本文介绍了是否可以制作两个 LiveData 的一个 LiveData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 DAO、两个存储库和两个 POJO.有什么方法可以创建两个的一个 Livedata?我需要它来为 Recyclerview 制作单个列表.POJO 是类似的对象.
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.
费用存储库:
public class ExpenseRepository {
private ExpenseDao expenseDao;
private LiveData<List<Expense>> allExpenses;
public ExpenseRepository(Application application) {
ExpenseIncomeDatabase database = ExpenseIncomeDatabase.getInstance(application);
expenseDao = database.expenseDao();
allExpenses = expenseDao.getExpensesByDay();
}
public LiveData<List<Expense>> getAllExpensesByDay() {
return allExpenses;
}
收入库:
public class IncomeRepository {
private IncomeDao incomeDao;
private LiveData<List<Income>> allIncomes;
public IncomeRepository(Application application) {
ExpenseIncomeDatabase database = ExpenseIncomeDatabase.getInstance(application);
incomeDao = database.incomeDao();
allIncomes = incomeDao.getIncomesByDay();
}
public LiveData<List<Income>> getAllIncomesByDay() {
return allIncomes;
}
费用道:
@Dao
public interface ExpenseDao {
@Query("SELECT * FROM expense_table ORDER BY day")
LiveData<List<Expense>> getExpensesByDay();
收入道:
@Dao
public interface IncomeDao {
@Query("SELECT * FROM income_table ORDER BY day")
LiveData<List<Income>> getIncomesByDay();
每日视图模型:
public class DailyFragmentViewModel extends AndroidViewModel {
private ExpenseRepository expenseRepository;
private IncomeRepository incomeRepository;
private LiveData<Pair<List<Expense>, List<Income>>> combined;
private ExpenseDao expenseDao;
private IncomeDao incomeDao;
public DailyFragmentViewModel(@NonNull Application application) {
super(application);
expenseRepository = new ExpenseRepository(application);
incomeRepository = new IncomeRepository(application);
combined = new DailyCombinedLiveData(expenseDao.getExpensesByDay(), incomeDao.getIncomesByDay());
}
public LiveData<Pair<List<Expense>, List<Income>>> getExpensesAndIncomes() {
return combined;
}
推荐答案
在 kotlin 中创建了这个扩展函数
Created this extension function in kotlin
fun <A, B> LiveData<A>.zipWith(stream: LiveData<B>): LiveData<Pair<A, B>> {
val result = MediatorLiveData<Pair<A, B>>()
result.addSource(this) { a ->
if (a != null && stream.value != null) {
result.value = Pair(a, stream.value!!)
}
}
result.addSource(stream) { b ->
if (b != null && this.value != null) {
result.value = Pair(this.value!!, b)
}
}
return result
}
这篇关于是否可以制作两个 LiveData 的一个 LiveData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!