sandrooco
sandrooco

Reputation: 8716

RxJs: How can I simplify this observable chain?

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.

Upvotes: 0

Views: 65

Answers (2)

olivarra1
olivarra1

Reputation: 3399

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');
  })
);

Upvotes: 2

Cemal BAYGIN
Cemal BAYGIN

Reputation: 46

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');
      })
    );

Upvotes: 1

Related Questions