9

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.

offbyone
  • 93
  • 1
  • 3
  • If you don't necessarily want to drop for some period of time, but rather drop as long as the processing is going on, you can [take advantage of the backpressure](https://stackoverflow.com/q/52966919/1916449). – arekolek Oct 24 '18 at 11:51

4 Answers4

6

I think throttleFirst is what you want: https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-throttlefirst

zsxwing
  • 20,270
  • 4
  • 37
  • 59
3

For preventing fast clicks i use this code

RxView.clicks(your_view)
            .throttleFirst(300, TimeUnit.MILLISECONDS)
            .subscribe {
                //on click
            }
Radesh
  • 13,084
  • 4
  • 51
  • 64
2

Continuing zsxwing's Answer:

If you're not using RxBinding library but only RxJava then,

io.reactivex.Observable.just(view_obj)
                .throttleFirst(1, TimeUnit.SECONDS)// prevent rapid click for 1 seconds
                .blockingSubscribe(o -> {                     
                    startActivity(...);
                });
Aks4125
  • 4,522
  • 4
  • 32
  • 48
-1

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());
      }
    });
shekar
  • 1,251
  • 4
  • 22
  • 31