【问题标题】:How to make RxJava interval to perform action instantly如何使 RxJava 间隔立即执行操作
【发布时间】:2018-05-19 18:24:54
【问题描述】:

您好,我正在让 observable 每 15 秒向我的服务器询问其在线/离线状态:

public Observable<Response> repeatCheckServerStatus(int intervalSec, final String path) {
        return Observable.interval(intervalSec, TimeUnit.SECONDS)
                .flatMap(new Func1<Long, Observable<Response>>() {
                    @Override
                    public Observable<Response> call(Long aLong) {
                        return Observable.create(new Observable.OnSubscribe<Response>() {
                            @Override
                            public void call(Subscriber<? super Response> subscriber) {
                                try {
                                    Response response = client.newCall(new Request.Builder()
                                            .url(path + API_ACTION_CHECK_ONLINE_STATUS)
                                            .header("Content-Type", "application/x-www-form-urlencoded")
                                            .get()
                                            .build()).execute();

                                    subscriber.onNext(response);
                                    subscriber.onCompleted();
                                    if (!response.isSuccessful())
                                        subscriber.onError(new Exception());
                                } catch (Exception e) {
                                    subscriber.onError(e);
                                }
                            }
                        })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread());
                    }
                });

    }

调用此方法后,代码的第一次执行将在 intervalSec 时间之后(在我的情况下为 15 秒)。查看间隔方法的rxJava文档:

http://reactivex.io/documentation/operators/interval.html

这是应该的。

问题:有什么方法可以立即执行代码,然后间隔重复?

【问题讨论】:

  • 接受的答案很棒。如果您真的希望它是“即时的”,我建议您查看观察调度程序本身。如果我们已经在 UI 线程上(Looper.myLooper() == Looper.getMainLooper()'). The startWith`,应该是同步,应该立即执行而不是发布到主线程以供以后使用,如果我们不在主线程上,则回退到 RxAndroid。

标签: java android rx-java


【解决方案1】:

你也可以像这样立即执行它:

Observable.interval(0, 1000, TimeUnit.MILLISECONDS).subscribe();

【讨论】:

  • 这确实应该是选择的答案
【解决方案2】:

你要找的是startWith

Observable.interval(15, SECONDS).startWith(1);

这将从间隔中获取更新,但在订阅后立即发出一项。

【讨论】:

    【解决方案3】:

    你可以使用`

    Observable.interval(1, TimeUnit.SECONDS).startWith(0)
    

    ` 在订阅中是重复值“0”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多