How to properly run subscription inside finalize in rxjs

New to rxjs. Have a bit of a situation which I find confusing.

The scenario is after clicking a button, a confirm modal would appear asking yes or no, then if the response is yes, the proceed to the switchMap call, and finally call a subscription at the end of the pipe regardless whether the result is yes or no.

my code sample:

.sendConfirmation().pipe(
  filter(result => result.answer === true),       
  switchMap(() => //only do stuff if result.answer === true),
  finalize(() =>  doAllTheTime()) //stuff i want to execute whether result.answer is true or false)
.subscribe()

I've tried this and this works as intended:

finalize(() => doAllTheTime().subscribe())

But from what I've read about observables it's not recommended to nest subscriptions, so I'm interested in knowing the best practice for situations like this.

Upvotes: 3

Views: 284

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55167

I'd handle the problem the other way : prevent the filter from filtering everything.

of(true).pipe(
  switchMap((myVal) => {
    if (myVal) {
      return of('someOperator');
    } else {
      return of('nothing');
    }
  }),
  switchMap(() => doAllTheTime()))
);

Or if you prefer you can also use the iif operator.

Upvotes: 2

Related Questions