Consider the following use case:
- need to deliver first item as soon as possible
- need to debounce following events with 1 second timeout
I ended up implementing custom operator based on OperatorDebounceWithTime
then using it like this
.lift(new CustomOperatorDebounceWithTime<>(1, TimeUnit.SECONDS, Schedulers.computation()))
CustomOperatorDebounceWithTime
delivers the first item immediately then uses OperatorDebounceWithTime
operator's logic to debounce later items.
Is there an easier way to achieve described behavior? Let's skip the compose
operator, it doesn't solve the problem. I'm looking for a way to achieve this without implementing custom operators.
Ngrx - rxjs solution, split the pipe to two
Use the version of
debounce
that takes a function and implement the function in this way:The first item emits immediately. Subsequent items are delayed by a second. If a delayed observable doesn't terminate before the following item arrives, it's cancelled, so the expected debounce behavior is fulfilled.
A simple solution using RxJava 2.0, translated from the answer for the same question for RxJS, which combines throttleFirst and debounce, then removes duplicates.
The approach of using limit() or take() don't seem to handle long lived data flows, where I might want to continually observe, but still act immediately for the first event seen for a time.
Update:
From @lopar's comments a better way would be:
Would something like this work:
The LordRaydenMK and lopar's answer has a problem: you always lose the second item. I supose that no one realeased this before because if you have a debounce you normally has a lot of events and the second is discarted with the debounce anyways. The correct way to never lost any event is:
And don't worry, you are not going to get any duplicated event. If you aren't sure about it you can run this code and check it yourself:
The answers by @LortRaydenMK and @lopar are best, but I wanted to suggest something else in case it happened to work better for you or for someone in a similar situation.
There's a variant of
debounce()
that takes a function that decides how long to debounce this particular item for. It specifies this by returning an observable that completes after some amount of time. Your function could returnempty()
for the first item andtimer()
for the rest. Something like (untested):The trick is that this function would have to know which item is the first. Your sequence might know that. If it doesn't, you might have to
zip()
withrange()
or something. Better in that case to use the solution in the other answer.