0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rxjs mergeMap concatMap switchMap exhaustMap

Last updated at Posted at 2021-08-20

if we need to do things in sequence while waiting for completion, then concatMap is the right choice

for doing things in parallel, mergeMap is the best option

in case we need cancellation logic, switchMap is the way to go

for ignoring new Observables while the current one is still ongoing, exhaustMap does just that

    const subject = new Subject<{ url: string; delay: number; }>();

    subject
      .pipe(
        //mergeMap(concurrent?: number)  concatMap   switchMap exhaustMap
        exhaustMap( httpGet
        ),
        map((res: string) => JSON.parse(res).ResultData)
      )
      .subscribe((value) => {
        let dateTime = new Date();
        console.log(value + "  " + dateTime.toLocaleTimeString());
      });

    let dateTime = new Date();
    console.log(dateTime.toLocaleTimeString());
    console.log("start http://foo ");
    subject.next({ url: 'http://foo', delay: 5000 });
    console.log("start http://bar ");
    subject.next({ url: 'http://bar', delay: 5000 });
    console.log("start http://baz ");
    subject.next({ url: 'http://baz', delay: 5000 });

    function httpGet(pram :{url: string, delay: number}) {
      return interval(1000).pipe(delay(pram.delay),take(4), map(val => {
        const obj = { ResultData: pram.url + ' -> ' + val };
        //console.log(JSON.stringify(obj));
        return JSON.stringify(obj);
      }))
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?