Created
January 23, 2019 15:44
-
-
Save curioustechizen/515803d94f89362fb7be9b433a464bfa to your computer and use it in GitHub Desktop.
Analog of RxJava's Observable.scan operator for Android Architecture Components LiveData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Analog of RxJava's Observable.scan operator. | |
* | |
* Returns a LiveData that applies the [accumulator] function to the fist item in the source LiveData, | |
* and an initial value, then feeds the result of that function along with the second item emitted by | |
* the source LiveData into the same function, and so on until all items have been emitted by the source | |
* LiveData, emitting the result of each of these iterations. | |
*/ | |
fun <T, R> LiveData<T>.scan(initialValue: R, accumulator: (R, T) -> R): LiveData<R> { | |
val returnLiveData = MediatorLiveData<R>() | |
returnLiveData.value = initialValue | |
returnLiveData.addSource(this) { | |
//TODO: get rid of the !! | |
val result = accumulator.invoke(returnLiveData.value!!, this.value!!) | |
returnLiveData.value = result | |
} | |
return returnLiveData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment