RxJava - Opposite of switchMap() Operator?
Sure, gate the processing of a value by a boolean that is set after the processing finished:
AtomicBoolean gate = new AtomicBoolean(true);
Observable.interval(200, TimeUnit.MILLISECONDS)
.flatMap(v -> {
if (gate.get()) {
gate.set(false);
return Observable.just(v).delay(500, TimeUnit.MILLISECONDS)
.doAfterTerminate(() -> gate.set(true));
} else {
return Observable.empty();
}
})
.take(10)
.toBlocking()
.subscribe(System.out::println, Throwable::printStackTrace);
Edit
Alternative:
Observable.interval(200, TimeUnit.MILLISECONDS)
.onBackpressureDrop()
.flatMap(v -> {
return Observable.just(v).delay(500, TimeUnit.MILLISECONDS);
}, 1)
.take(10)
.toBlocking()
.subscribe(System.out::println, Throwable::printStackTrace);
You can change onBackpressureDrop
to onBackpressureLatest
to continue immediately with the latest value.
I know that this an old thread but currently there is a RxJs operator that does just that.
The operator is exhaustMap
.
According to the docs:
ExhaustMap projects each source value to an Observable which is merged in the output Observable only if the previous projected Observable has completed.
Docs example:
import { fromEvent, interval } from 'rxjs';
import { exhaustMap, take } from 'rxjs/operators';
const clicks = fromEvent(document, 'click');
const result = clicks.pipe(
exhaustMap(ev => interval(1000).pipe(take(5)))
);
result.subscribe(x => console.log(x));