开发者

How to handle condition inside mergeMap?

开发者 https://www.devze.com 2022-12-07 22:45 出处:网络
Obs1$.pipe( mergeMap((data) => { if (data.condition) { const generatedStuff = doSomethingFunction(data1);
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:

T开发者_C百科ype 'Subject<void> | undefined' is not assignable to type 'ObservableInput<any>'.
    Type 'undefined' is not assignable to type 'ObservableInput<any>'.ts(2345)


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


You could simply just use kind of local state variable. In merge map its assigned and inside subscription handler its checked:

import { EMPTY } from 'rxjs';

let cond = false

Obs1$.pipe(
  mergeMap((data) => {

    cond = data.condition        

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

    someCleanupAction();

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

精彩评论

暂无评论...
验证码 换一张
取 消