Created
May 29, 2017 06:50
-
-
Save yosriz/7f60bbd45c65db0c11ee01105a9958f6 to your computer and use it in GitHub Desktop.
RxJava2 Exhaust Map - ignore (drop) incoming requests while work is in progress
This file contains 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
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