Skip to content

Instantly share code, notes, and snippets.

@curioustechizen
Created January 23, 2019 15:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curioustechizen/515803d94f89362fb7be9b433a464bfa to your computer and use it in GitHub Desktop.
Save curioustechizen/515803d94f89362fb7be9b433a464bfa to your computer and use it in GitHub Desktop.
Analog of RxJava's Observable.scan operator for Android Architecture Components LiveData
/**
* 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