问题
I am writing an android app and using rxjava to handle user input events. Basically what I want to do is, emit when a button is clicked, and then drop subsequent emissions for some period of time afterwards (like a second or two), essentially to prevent having to process multiple clicks of the button.
回答1:
I think throttleFirst
is what you want: https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlefirst
回答2:
For preventing fast clicks i use this code
RxView.clicks(your_view)
.throttleFirst(300, TimeUnit.MILLISECONDS)
.subscribe {
//on click
}
回答3:
Continuing zsxwing's Answer:
If you're not using RxBinding library but only RxJava then,
io.reactivex.Observable.just(new Object())
.throttleFirst(1, TimeUnit.SECONDS)// prevent rapid click for 1 seconds
.blockingSubscribe(o -> {
startActivity(...);
});
回答4:
This can be done with share debounce and buffer operator
Observable<Object> tapEventEmitter = _rxBus.toObserverable().share();
Observable<Object> debouncedEventEmitter = tapEventEmitter.debounce(1, TimeUnit.SECONDS);
Observable<List<Object>> debouncedBufferEmitter = tapEventEmitter.buffer(debouncedEventEmitter);
debouncedBufferEmitter.buffer(debouncedEventEmitter)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<Object>>() {
@Override
public void call(List<Objecenter code heret> taps) {
_showTapCount(taps.size());
}
});
来源:https://stackoverflow.com/questions/22204774/preventing-rapid-clicks-with-rxjava