How to make RxJava interval for instant action

Hi, I make it noticeable to ask my server about its online / offline status every month:

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

    }

After I call this method, the first code execution will be executed after the time interval S seconds (15 seconds in my case). Looking at the rxJava documentation of the interval method:

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

This is how it should be.

Question: is there a way to execute the code instantly and then repeat at intervals?

+4
source share
2 answers

What you are looking for startWith

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

This will receive updates from the interval, but immediately after the subscription release one item.

+4
source

:

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

Source: https://habr.com/ru/post/1625653/


All Articles