I want to transform my source Flowable in such a way that events only go though if they are the first item within a specified period.
That is, I want the first item to go through and then drop all subsequent items until there was a period of, say, 10 seconds, in which no upstream event arrived.
Note that is this neither
debounce
: This would emit each item iff it was not followed by another one for 10 seconds - but this will force a 10 second delay on even the first item. I want to emit the first item right away.throttleFirst
: This would emit the first item and then drop all subsequent items for 10 seconds after that first one. I want to have the blocking period reset after each upstream item.
I've now solved it like this:
source
.flatMap { Flowable.just(1).concatWith(Flowable.just(-1).delay(10, TimeUnit.SECONDS)) }
.scan(0, { x, y -> x + y })
.map { it > 0 }
.distinctUntilChanged()
.filter { it }
NOTE: I don't care about the actual items in source
, only that they occur - but, of course, I could just wrap the items in a Pair
along with 1
or -1
).
Is there a simpler way to use built-in RxJava(2) Operators to achieve the same goal?