How to handle condition inside mergeMap?

151 Views Asked by At
Obs1$.pipe(
  mergeMap((data) => {
    if (data.condition) {
      const generatedStuff = doSomethingFunction(data1);
      return generatedStuff.Obs2$;
    }

    someCleanupAction();

    return of(null); // I want to get rid this because I don't want doSomethingElse() to be called when a condition is false happens
  })
).subscribe(() => {
  doSomethingElse();
})

The above is my current code based on https://stackoverflow.com/a/74552146/5195033.

Like my comment above, I just I want doSomethingElse() to be called when the condition is true.

Expectedly, commenting out return of(null); gives:

Type 'Subject<void> | undefined' is not assignable to type 'ObservableInput<any>'.
    Type 'undefined' is not assignable to type 'ObservableInput<any>'.ts(2345)
1

There are 1 best solutions below

1
On BEST ANSWER

You can return EMPTY instead of of(null).

import { EMPTY } from 'rxjs';

Obs1$.pipe(
  mergeMap((data) => {
    if (data.condition) {
      const generatedStuff = doSomethingFunction(data1);
      return generatedStuff.Obs2$;
    }

    someCleanupAction();

    return EMPTY
  })
).subscribe(() => {
  doSomethingElse();
})