Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debounce a retrofit reactive request in java?

I'm working on an android project that makes requests through retrofit using Rx-Java observable and subscribe.

However, in some interactions this request can be called multiple times and I would like to only execute the last one in a predefined window of time (debounce).

I tried to apply the debounce operator directly to the observable, but it will not work because the code below is executed every time some interaction occurs:

mApi.getOnlineUsers()
    .debounce(1, TimeUnit.SECONDS)
    .subscribe(...)

I guess it should be created only one observable and every interaction it should "append" the execution to the same observable. But I am kind of new on Rx Java and don't know exactly what to do.

Thanks!

like image 636
Luccas Avatar asked Oct 21 '15 21:10

Luccas


1 Answers

Suppose you want to start an execution according to some trigger event.

Observable<Event> trigger = ... // e.g. button clicks

You can transform the trigger events to calls to your API like this:

trigger
    .debounce(1, TimeUnit.SECONDS)
    .flatMap(event -> mApi.getOnlineUsers())
    .subscribe(users -> showThemSomewhere(users));

Also, notice that the debounce operator will take the last occurrence within the time frame, but throttlefirst will take the first. You may want to use one or the other depending on your use case.

like image 144
ESala Avatar answered Oct 16 '22 18:10

ESala