【问题标题】:Is it possible to make one LiveData of two LiveDatas?是否可以制作两个 LiveData 的一个 LiveData?
【发布时间】:2019-03-07 12:54:21
【问题描述】:

我有两个 DAO、两个存储库和两个 POJO。有什么方法可以创建两个的 Livedata?我需要它为 Recyclerview 制作单个列表。 POJO 是类似的对象。

ExpenseRepository:

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();

DailyViewModel:

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;
}

【问题讨论】:

  • 检查MediatorLiveData
  • 嗯,看起来像是 MediatorLiveData 的一个用例。 PS我不确定,因为我从未使用过它。深入阅读。

标签: android android-room android-livedata


【解决方案1】:

我假设您想将它们结合起来,是吗?你需要一个 MediatorLiveData,但是说你现在需要 Object 的人是错误的。你需要的是MediatorLiveData&lt;Pair&lt;List&lt;Expense&gt;, List&lt;Income&gt;&gt;&gt;。

public class CombinedLiveData extends MediatorLiveData<Pair<List<Expense>, List<Income>>> {
    private List<Expense> expenses = Collections.emptyList();
    private List<Income> incomes = Collections.emptyList();

    public CombinedLiveData(LiveData<List<Expense>> ld1, LiveData<List<Income>> 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));
        });
    }
}

您可能会将此通用化,它是使用 2 元组(对)的两个 LiveData 实现 combineLatest。

编辑:像这样:

public class CombinedLiveData2<A, B> extends MediatorLiveData<Pair<A, B>> {
    private A a;
    private B b;

    public CombinedLiveData2(LiveData<A> ld1, LiveData<B> 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));
        });
    }
}

请注意,在这种情况下,我无法将Collections.emptyList() 设置为A 和B 的初始值,当您访问该对中的数据时,您需要检查nulls。

编辑:您可以使用库 https://github.com/Zhuinden/livedata-combinetuple-kt (Kotlin) 或 https://github.com/Zhuinden/livedata-combineutil-java/ (Java) 来做同样的事情。

【讨论】:

  • 在这种情况下,如果expenses livedata 被触发,那么income 数据也将可用,它可能是空数据或旧数据。我认为实现一个泛型类将是一个合适的解决方案。
  • 它永远不会为空,但它可以是空列表。这是否符合预期取决于您是否需要 zip 或 combineLatest。您可能会使用布尔值跟踪“确实发出”,当所有这些都为真时发出一次?
  • 看起来很有趣。我应该创建 CombinedLiveData 类,还是为这个公共存储库制作?
  • 好吧,我所知道的是,如果您将这个调解器实例作为LiveData&lt;Pair&lt;List&lt;Expense&gt;, List&lt;Income&gt;&gt;&gt; 接收,那么您将收到这两个参数,只要它们中的任何一个发生变化。我认为在 ViewModel 中您可以像 new CombinedLiveData(dao.findExpenses(), dao.findIncomes()) 一样创建它,它会起作用。
  • 嗯,你应该能够使用两种不同的 ViewType,只要你将两个 List 都传递给适配器,但是 diffing 列表很复杂。为此,简单的出路是使用可以“统一处理多种视图类型的方式”的库,例如github.com/lisawray/groupie。
【解决方案2】:

在 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
}

【讨论】:

    【解决方案3】:

    不是让一个类添加 2 个实时数据,另一个类添加 3 个实时数据等。我们可以使用更抽象的方式添加任意数量的实时数据。

    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MediatorLiveData
    
    /**
     * CombinedLiveData is a helper class to combine results from multiple LiveData sources.
     * @param liveDatas Variable number of LiveData arguments.
     * @param combine   Function reference that will be used to combine all LiveData data.
     * @param R         The type of data returned after combining all LiveData data.
     * Usage:
     * CombinedLiveData<SomeType>(
     *     getLiveData1(),
     *     getLiveData2(),
     *     ... ,
     *     getLiveDataN()
     * ) { datas: List<Any?> ->
     *     // Use datas[0], datas[1], ..., datas[N] to return a SomeType value
     * }
     */
    class CombinedLiveData<R>(vararg liveDatas: LiveData<*>,
                              private val combine: (datas: List<Any?>) -> R) : MediatorLiveData<R>() {
    
        private val datas: MutableList<Any?> = MutableList(liveDatas.size) { null }
    
        init {
            for(i in liveDatas.indices){
                super.addSource(liveDatas[i]) {
                    datas[i] = it
                    value = combine(datas)
                }
            }
        }
    }
    

    【讨论】:

    • 这可以用来传递不同泛型类型的livedata列表吗?以及如何使用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多