2

I have add button in my app to let user add item to a list, if user clicks the add button i dont the request to go to the webservice immediately, I want the request to be accumulated and sent every 1 seconds with the total number of clicks. instead of sending the request every time the user clicks the add button.

I saw that there is something like this implemented for RxSearchView. I checked the code it is too complicated

I need some help with where should I start with such a problem ? or any ready solution for this ?

Maksim Ostrovidov
  • 10,720
  • 8
  • 42
  • 57
MBH
  • 16,271
  • 19
  • 99
  • 149

1 Answers1

3

You are looking for debounce operator:

Returns an Observable that mirrors the source ObservableSource, except that it drops items emitted by the source ObservableSource that are followed by newer items before a timeout value expires. The timer resets on each emission.enter image description here

Just wrap your click events into Observable:

Observable<Object> getButtonObservable(final Button button) {
    return Observable.create(new ObservableOnSubscribe<Object>() {
        @Override
        public void subscribe(final ObservableEmitter<Object> e) throws Exception {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    e.onNext(new Object()); //instead of Object you can use any data, e.g. derived from View tag
                }
            });
            e.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    button.setOnClickListener(null);
                }
            });
        }
    });
}

And apply that operator not forgetting to unsubscribe in onDestroy (onDestroyView):

Button addButton;
Disposable addButtonDisposable;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    getButtonObservable(addButton)
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    addButtonDisposable = disposable;
                }
            })
            .debounce(1, TimeUnit.SECONDS)
            ... //make request using flatMap or doOnNext, and subscribe
}

@Override
protected void onDestroy() {
    super.onDestroy();
    addButtonDisposable.dispose();
}
Maksim Ostrovidov
  • 10,720
  • 8
  • 42
  • 57