Skip to content

Instantly share code, notes, and snippets.

@crimsonwoods
Created July 28, 2021 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crimsonwoods/61002e05b16434d0819a9ef8af8ef483 to your computer and use it in GitHub Desktop.
Save crimsonwoods/61002e05b16434d0819a9ef8af8ef483 to your computer and use it in GitHub Desktop.
import io.reactivex.Observable
/**
* RxJavaのStreamに流れる一つ前の値と現在の値をひとまとめにするための型
*/
data class Change<T : Any>(
val previous: T?,
val current: T,
)
/**
* Observableに流れてくる一つ前の値と現在の値をひとまとめにした型に変換するoperator
*/
fun <T : Any> Observable<T>.changes(): Observable<Change<T>> {
return scan(emptyList()) { list: List<T>, value: T ->
(list + value).takeLast(2)
}.filter {
it.isNotEmpty()
}.map { values ->
when (values.size) {
1 -> Change(null, values[0])
2 -> Change(values[0], values[1])
else -> throw IllegalStateException()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment