How do I make an Observable Interval start immediately without a delay?

后端 未结 3 709
醉梦人生
醉梦人生 2020-12-20 11:13

I want my observable to fire immediately, and again every second. interval will not fire immediately. I found this question which suggested using startWith, whi

相关标签:
3条回答
  • 2020-12-20 11:18

    Before RxJs 6:

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

    RxJs 6+

    import {timer} from 'rxjs/observable/timer';
    timer(0, 1000).subscribe(() => { ... });
    
    0 讨论(0)
  • 2020-12-20 11:33

    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.

    0 讨论(0)
  • 2020-12-20 11:44

    RxJs 6

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

    or with timer:

    import {timer} from 'rxjs/observable/timer';
    timer(0, 100).subscribe(() => {
    
        });
    
    0 讨论(0)
提交回复
热议问题