{

Multiple ways to Create an Observable with Delay| Angular examples


This tutorial shows an example of creating an observable with delay in angular and typescript.

Observable are objects in RXJS for asynchronous operations Angular application.

We already have a how to create an obeservable array in Angular

How to create an observable with delay in Angular?

-Create an array of type strings and initialized them with string values.

  • Create an array of an observable array using () from rxjs. And pipe is used to attach delay operation with 4000 milliseconds.
  private myarray: string[] = ["test", "test2", "test3"]
  array1: Observable<string[]> = of(this.myarray).pipe(delay(4000));

Here is an angular complete code

import { Component } from '@angular/core';
import { delay, from, Observable, of, take, tap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  private myarray: string[] = ["test", "test2", "test3"]
  array1: Observable<string[]> = of(this.myarray).pipe(delay(5000));

  private result: string[] = [];
  constructor() {
    console.log("start")
    this.array1.subscribe(item => console.log(item));
    console.log("end")
  }

}

You would see the console log as follows and prints the array after 4 seconds.

start
end
['test', 'test2', 'test3']

Suppose you want to delay with a timer for every array element.

concatMap is used to map with again observable string with the delay of 3 seconds

  private myarray: string[] = ["test", "test2", "test3"]
  strings$: Observable<string[]> = of(this.myarray);
  result: Observable<string> = from(this.myarray).pipe(concatMap(item => of(item).pipe(delay(3000))));

Here is an angular code displays 3 seconds for array element

import { Component } from '@angular/core';
import { concatMap, delay, from, Observable, of, take, tap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  private myarray: string[] = ["test", "test2", "test3"]
  strings$: Observable<string[]> = of(this.myarray);
  result: Observable<string> = from(this.myarray).pipe(concatMap(item => of(item).pipe(delay(3000))));

  constructor() {
    console.log("start")
    this.result.subscribe(item => console.log(item));
    console.log("end")
  }

}

Each array element is printed to console with a delay of 3 seconds Output:

start
end
test
test2
test3
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.