【问题标题】:Use RxJava to make a periodic Retrofit request with ambWith and mergeWith?使用 RxJava 通过 ambWith 和 mergeWith 发出定期改造请求?
【发布时间】:2018-02-08 04:30:42
【问题描述】:

我想在 Android 应用中使用 RxJava 实现一个重复的 http 请求,满足以下要求:

  1. 应每 2 秒发出一次请求。

  2. 请求最多每 2 秒发出一次。

  3. 如果请求在 2 秒后超时,我们应该取消请求。

这是我的 RestService:

public interface RestService {    
    @GET("name")
    Single<String> getName();
}

我在网上做了一些研究,这是我在这个链接之后实现的:Periodic HTTP Requests Using RxJava and Retrofit

Observable.interval(2, TimeUnit.SECONDS, Schedulers.io())
        .map((tick) -> restService.getName())
        .subscribe(name -> Log.v("sampleApp", "received " + name));

我测试了上面的代码,我认为它满足要求 #1。但我不确定如何调整它以实现要求#2 和#3?

我看到了一些使用 ambWith 和 mergeWith 的示例,但我不太了解它们。如果有人可以解释它们或指出可以很好地解释它们的资源,我将不胜感激!

谢谢!

【问题讨论】:

    标签: retrofit rx-java retrofit2 rx-java2


    【解决方案1】:

    我相信#2 也对您的示例感到满意。至于超时,只需在 restService.getName() 之后添加 .timeout(long timeout, java.util.concurrent.TimeUnit timeUnit),即在 内。顺便说一下,map() 应该是 .flatMap()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 2021-05-19
      • 1970-01-01
      • 2019-02-28
      • 2023-03-17
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多