如何在Java中对改装的反应式请求进行反跳动? [英] How to debounce a retrofit reactive request in java?

查看:112
本文介绍了如何在Java中对改装的反应式请求进行反跳动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个Android项目,该项目可通过使用Rx-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).

我尝试将 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(...)

我猜应该只创建一个可观察的对象,并且每次交互都应该将执行附加"到相同的可观察对象.但是我对Rx Java还是陌生的,不知道该怎么做.

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.

谢谢!

推荐答案

假设您要根据某个触发事件开始执行.

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

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

您可以将触发事件转换为对API的调用,如下所示:

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));

此外,请注意, debounce 运算符将在时间范围内将 last 发生在事件中,而 throttlefirst 将在事件发生时将 first.根据您的用例,您可能要使用其中一个.

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.

这篇关于如何在Java中对改装的反应式请求进行反跳动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆