How to combine two live data one after the other?

前端 未结 7 1770
佛祖请我去吃肉
佛祖请我去吃肉 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
    慢半拍i (楼主)
    2020-12-13 05:41

    if you want both value not null

    fun  LiveData.combineWithNotNull(
            liveData: LiveData,
            block: (T, V) -> R
    ): LiveData {
        val result = MediatorLiveData()
        result.addSource(this) {
            this.value?.let { first ->
                liveData.value?.let { second ->
                    result.value = block(first, second)
                }
            }
        }
        result.addSource(liveData) {
            this.value?.let { first ->
                liveData.value?.let { second ->
                    result.value = block(first, second)
                }
            }
        }
    
        return result
    }
    

提交回复
热议问题