Created
July 28, 2021 12:40
-
-
Save crimsonwoods/61002e05b16434d0819a9ef8af8ef483 to your computer and use it in GitHub Desktop.
This file contains 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
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