Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rxjs

reactivex

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?

like image 468
adamdport Avatar asked May 24 '17 18:05

adamdport


People also ask

What is observable interval?

interval returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between those emissions. The first emission is not sent immediately, but only after the first period has passed.

How do you use RxJS interval?

RxJS interval() Creation OperatorRxJS interval() operator is a creation operator used to create an observable that emits a sequence of integers every time for the given time interval on a specified SchedulerLike. It emits incremented numbers periodically in time.

How do I stop RxJS interval?

Just unsubscribe: import { interval } from 'rxjs'; const subscription = interval(1000) .


2 Answers

Before RxJs 6:

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

RxJs 6+

import {timer} from 'rxjs/observable/timer'; timer(0, 1000).subscribe(() => { ... }); 
like image 120
Julia Passynkova Avatar answered Sep 24 '22 07:09

Julia Passynkova


RxJs 6. Note: With this solution, 0 value will be emitted twice (one time immediately by startWith, and one time by interval stream after the first "tick", so if you care about the value emitted, you could consider startWith(-1) instead of startWith(0)

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

or with timer:

import {timer} from 'rxjs/observable/timer'; timer(0, 100).subscribe(() => {      }); 
like image 30
robert king Avatar answered Sep 23 '22 07:09

robert king