How do I make an Observable Interval start immedia

2020-02-13 07:30发布

I want my observable to fire immediately, and again every second. interval will not fire immediately. I found this question which suggested using startWith, which DOES fire immediately, but I then get a duplicate first entry.

  Rx.Observable.interval(1000).take(4).startWith(0).subscribe(onNext);

https://plnkr.co/edit/Cl5DQ7znJRDe0VTv0Ux5?p=preview

How can I make interval fire immediately, but not duplicate the first entry?

3条回答
来,给爷笑一个
2楼-- · 2020-02-13 07:36

Observable.timer(0, 1000) will start immediately.

查看更多
The star\"
3楼-- · 2020-02-13 07:52

RxJs 6

interval(100).pipe(startWith(0)).subscribe(() => { //your code }); 

or with timer:

import {timer} from 'rxjs/observable/timer';
timer(0, 100).subscribe(() => {

    });
查看更多
Root(大扎)
4楼-- · 2020-02-13 08:01

With RxJava2, there's no issue with duplicated first entry and this code is working fine:

io.reactivex.Observable.interval(1, TimeUnit.SECONDS)
        .startWith(0L)
        .subscribe(aLong -> {
            Log.d(TAG, "test");    // do whatever you want
    });

Note you need to pass Long in startWith, so 0L.

查看更多
登录 后发表回答