Skip to content

Instantly share code, notes, and snippets.

@yosriz
Created May 29, 2017 06:50
Show Gist options
  • Save yosriz/7f60bbd45c65db0c11ee01105a9958f6 to your computer and use it in GitHub Desktop.
Save yosriz/7f60bbd45c65db0c11ee01105a9958f6 to your computer and use it in GitHub Desktop.
RxJava2 Exhaust Map - ignore (drop) incoming requests while work is in progress
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;
class ExhaustMapTransformer<Upstream, Downstream> implements ObservableTransformer<Upstream, Downstream> {
private final AtomicBoolean workInProgress = new AtomicBoolean(false);
private final Function<Upstream, Observable<Downstream>> mapper;
public ExhaustMapTransformer(Function<Upstream, Observable<Downstream>> mapper) {
this.mapper = mapper;
}
@Override
public Observable<Downstream> apply(Observable<Upstream> upstream) {
return upstream.flatMap(t -> {
if (workInProgress.compareAndSet(false, true)) {
return mapper.apply(t)
.doOnTerminate(() -> workInProgress.set(false));
} else {
return Observable.empty();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment