How to combine two live data one after the other?

前端 未结 7 1771
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 05:13

I have next use case: User comes to registration form, enters name, email and password and clicks on register button. After that system needs to check if email is taken or n

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 05:40

    I did an approach based on @guness answer. I found that being limited to two LiveDatas was not good. What if we want to use 3? We need to create different classes for every case. So, I created a class that handles an unlimited amount of LiveDatas.

    /**
      * 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 results.
      * @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)
                 }
             }
         }
     }
    

提交回复
热议问题