Created
February 4, 2019 06:15
-
-
Save kiwiandroiddev/7e730f1727b7e97d401327b15c48cc86 to your computer and use it in GitHub Desktop.
Allows a stream to be filtered with a predicate that evaluates the latest and previous items.
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
/** | |
* Filters items emitted by an observable by only emitting those that satisfy the specified | |
* predicate based on the latest and previous items emitted. | |
* Note that this will always filter out the first item of the stream since in this case there | |
* is as of yet no previous item to compare it to. | |
* | |
* @param bipredicate | |
* a function that evaluates the current and previous item emitted by the source ObservableSource, returning {@code true} | |
* if it passes the filter | |
* @return an Observable that emits only those items emitted by the source ObservableSource that the filter | |
* evaluates as {@code true} | |
*/ | |
fun <T> Observable<T>.filterWithBiPredicate(bipredicate: (T, T) -> Boolean): Observable<T> { | |
return this.buffer(2, 1) | |
.filter { buffer -> buffer.size == 2 } | |
.filter { lastTwoItems -> | |
val (old, current) = lastTwoItems | |
bipredicate(old, current) | |
} | |
.map { lastTwoItems -> lastTwoItems[1] } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment