Categories
TypeScript Answers

How to create an observable with a delay with Rxjs?

Spread the love

Sometimes, we want to create an observable with a delay with Rxjs.

In this article, we’ll look at how to create an observable with a delay with Rxjs.

How to create an observable with a delay with Rxjs?

To create an observable with a delay with Rxjs, we can use the from observable with the delay and concatMap operators.

For instance, we write

import { from, of } from "rxjs";
import { delay } from "rxjs/internal/operators";
import { concatMap } from "rxjs/internal/operators";

const myArray = [1, 2, 3];

from(myArray)
  .pipe(concatMap((item) => of(item).pipe(delay(1000))))
  .subscribe((timedItem) => {
    console.log(timedItem);
  });

to create an observer from the myArray array with from.

Then we call pipe with the concatMap operator called with a callback that returns an of observable that’s delayed with the delay by 1000 milliseconds.

Conclusion

To create an observable with a delay with Rxjs, we can use the from observable with the delay and concatMap operators.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *