简体   繁体   中英

RxJs 6 - React to concatMap in filter or takeWhile condition

I use concatMap to do two API calls consecutively, but the second one should only be run if a checkbox is checked. So this is my code:

this.myService.createArticle(article)
  .pipe(
    filter(() => this.checkbox),
    concatMap(() => return this.mailer.createOtherResource(data)),
  }).subscribe(
    (x) => { console.log('OK', x); },
    error => console.error('FALLA', error),
    () => console.log('Finally I have really reached the END')
  );

The thing is that, if the check box is not checked, even if the first observable does not return an error, the OK function is never run, only the 'finally' one, and I need it to inform the user that the resource was created. What can I do?

I tried with takeWhile instead pipe , and same result.

The last callback of your subscribe is ran only for the second call. If you want the first HTTP call to call a method once done, try this :

this.myService.createArticle(article)
  .pipe(
    finalize(() => console.log('Finally I have really reached the END (of the first call)'))
    filter(() => this.checkbox),
    concatMap(() => return this.mailer.createOtherResource(data)),
  }).subscribe(
    (x) => { console.log('OK', x); },
    error => console.error('FALLA', error),
    () => console.log('Finally I have really reached the END')
  );

I don't know what's returned by your createOtherResource function but is it an Observable ?

Maybe you should try this :

this.myService.createArticle(article)
  .pipe(
    filter(() => this.checkbox),
    concatMap(() => of(this.mailer.createOtherResource(data))),
  })
  .subscribe(
    (x) => console.log('OK', x),
    error => console.error('FALLA', error),
    () => console.log('Finally I have really reached the END')
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM