Is it possible to make one LiveData of two LiveDatas?

前端 未结 3 1924
醉梦人生
醉梦人生 2020-12-03 18:59

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.<

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 19:11

    Instead of having a class to add 2 live datas, another class to add 3 live datas, etc. We can use a more abstract way where we can add as many live datas as we want.

    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(
     *     getLiveData1(),
     *     getLiveData2(),
     *     ... ,
     *     getLiveDataN()
     * ) { datas: List ->
     *     // Use datas[0], datas[1], ..., datas[N] to return a SomeType value
     * }
     */
    class CombinedLiveData(vararg liveDatas: LiveData<*>,
                              private val combine: (datas: List) -> R) : MediatorLiveData() {
    
        private val datas: MutableList = MutableList(liveDatas.size) { null }
    
        init {
            for(i in liveDatas.indices){
                super.addSource(liveDatas[i]) {
                    datas[i] = it
                    value = combine(datas)
                }
            }
        }
    }
    

提交回复
热议问题