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?
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.
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.
Just unsubscribe: import { interval } from 'rxjs'; const subscription = interval(1000) .
Before RxJs 6:
Observable.timer(0, 1000)
will start immediately.
RxJs 6+
import {timer} from 'rxjs/observable/timer'; timer(0, 1000).subscribe(() => { ... });
RxJs 6. Note: With this solution,
0
value will be emitted twice (one time immediately bystartWith
, and one time byinterval
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(() => { });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With