How to combine two live data one after the other?

前端 未结 7 1742
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  -上瘾入骨i
    2020-12-13 05:48

    With the help of MediatorLiveData, you can combine results from multiple sources. Here an example of how would I combine two sources:

    class CombinedLiveData(source1: LiveData, source2: LiveData, private val combine: (data1: T?, data2: K?) -> S) : MediatorLiveData() {
    
    private var data1: T? = null
    private var data2: K? = null
    
    init {
        super.addSource(source1) {
            data1 = it
            value = combine(data1, data2)
        }
        super.addSource(source2) {
            data2 = it
            value = combine(data1, data2)
        }
    }
    
    override fun  addSource(source: LiveData, onChanged: Observer) {
        throw UnsupportedOperationException()
    }
    
    override fun  removeSource(toRemove: LiveData) {
        throw UnsupportedOperationException()
    }
    }
    

    here is the gist for above, in case it is updated on the future: https://gist.github.com/guness/0a96d80bc1fb969fa70a5448aa34c215

提交回复
热议问题