RxJS Operators: interval
Steven Boyd-Thompson
Posted on June 13, 2023
RxJS is a JavaScript library that enables the creation of asynchronous and event-based programs. The main type is the Observable
and a suite of functions and operators are provided to make it easier to work with the data coming through. This series will detail those operators (and a few stand-alone functions) and provide examples of their use.
In this post, we’re going to cover the interval
function.
What does it do?
Like the of
function, this isn’t an operator. I realised in a lot of the examples I was putting together I had implemented my version of interval
. This was adding pointless complications to the examples just to avoid using something we hadn’t discussed. So I’m covering it now to simplify future examples. So what does it do?
The interval
function is called with a time in milliseconds. When that time interval is reached it will emit a progressively incrementing number.
Example
The usage looks like this:
import { interval } from 'rxjs';
interval(1000).subscribe(x => {
console.log(x);
});
If we run this we will see a number written to the console every second, starting at 0 and incrementing from there. That’s all there is to it. This may not seem like much, but let's take a look at what it’s replacing. Originally I had this:
import { BehaviorSubject, Observable } from "rxjs";
const value$ = new BehaviorSubject<number>(0);
export function getObservable(): Observable<number> {
return value$.asObservable();
}
export function start(): void {
setInterval(() => {
const count = value$.getValue() + 1;
value$.next(count);
}, 1000);
}
Using interval
means I can get rid of that entire file and replace it with:
interval(1000);
Getting exactly the same behaviour. As you can see, this will simplify all the examples and allow us to focus on the operators being discussed.
The source code for this example is available on GitHub:
Posted on June 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.