Thursday, December 22, 2022

RxJS switchmap example

 RxJS switchmap example, easy to understand

https://stackblitz.com/edit/rxjs-switchmap-example-1-vslesu?file=index.ts

import { interval } from 'rxjs';
import { take, switchMap, map, flatmap } from 'rxjs/operators';

let outer$ = interval(5000).pipe(take(2));

let combined$ = outer$.pipe(
switchMap((x) => {
return interval(2000).pipe(
take(3),
map((y) => `outer ${x}: inner ${y}`)
);
})
);

/*
5 seconds: the inner observable is started
7 seconds: 0 0
9 seconds: 0 1
10 seconds (now the second outer$ comes, the inner observable is unsubscribed)
12 seconds: 1 0
14 seconds: 1 1
16 seconds: 1 2
*/

console.log(new Date().toISOString());
combined$.subscribe((result) =>
console.log(new Date().toISOString() + ' ' + `${result}`)
);


No comments:

Post a Comment