此LiveData组合代码如何工作?

时间:2019-07-02 10:53:39

标签: oop kotlin extension-methods

我发现了一篇有关LiveData(https://medium.com/androiddevelopers/livedata-beyond-the-viewmodel-reactive-patterns-using-transformations-and-mediatorlivedata-fda520ba00b7)的有趣帖子

在奖金部分,作者构建了MediatorLiveData扩展

let totalPoints = models.reduce(0) { (result, model) -> Int in
    if model.isYesSelected {
        return result + 1
    }
    return 0
}
print(totalPoints)

在存储库中看起来像

/**
* Sets the value to the result of a function that is called when both 
`LiveData`s have data
* or when they receive updates after that.
*/
fun <T, A, B> LiveData<A>.combineAndCompute(other: LiveData<B>, onChange: (A,  
B) -> T): MediatorLiveData<T> {

var source1emitted = false
var source2emitted = false

val result = MediatorLiveData<T>()

val mergeF = {
   val source1Value = this.value
   val source2Value = other.value

   if (source1emitted && source2emitted) {
       result.value = onChange.invoke(source1Value!!, source2Value!! )
   }
}

result.addSource(this) { source1emitted = true; mergeF.invoke() }
result.addSource(other) { source2emitted = true; mergeF.invoke() }

return result
}

我想知道“ UserDataSuccess”的实现是什么样的。我不太了解onChange部分发生了什么。

0 个答案:

没有答案