How to debounce a retrofit reactive request in java?

拟墨画扇 提交于 2019-12-19 05:23:19

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/33269954/how-to-debounce-a-retrofit-reactive-request-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!