Home > other >  RxJs: How can I simplify this observable chain?
RxJs: How can I simplify this observable chain?

Time:06-10

I have an observable chain that creates inner observables based on conditions. See the inner switchMap in the following example:

this.init().pipe(
  switchMap(() => {
    return this.structureService.get(...).pipe(
      switchMap((structure) => {
        // update structure if it has changes
        if (structure.changed) {
          return this.structureService.update(...);
        }

        // don't do anything if there are no changes
        return of({}); // I don't like this
      })
    );
  }),
  tap(()=> {
    console.log('done');
  })
);

I don't like to return of({}); because it's not what actually happens but solely serves the purpose of emitting when nothing has to be updated. Maybe this is doable with mergeMap - I tried but couldn't wrap my head around it.

CodePudding user response:

It's not fully equivalent, because it might depend on what's happening in each switchMap, but in general you can flatten them out, and with filter you will avoid the of({}):

this.init().pipe(
  switchMap(() => this.structureService.get(...))
  filter(structure => structure.changed),
  switchMap(() => this.structureService.update(...)),
  tap(()=> {
    console.log('done');
  })
);

CodePudding user response:

Maybe you prefer a minified code?

this.init().pipe(
      switchMap(() => this.structureService.get(...).pipe(
          switchMap((structure) => 
            structure.changed ? this.structureService.update(...) : of({})
          )
        )
      ),
      tap(()=> {
        console.log('done');
      })
    );
  • Related