chrispalmo
chrispalmo

Reputation: 247

Nested RxJS subscriptions - what is the right way to achieve this?

This is what I want to achieve:

this.actions$.pipe(
    ofActionDispatched(SomeAction, takeUntil(this.onDestroy$)).subscribe(() => {
        if (FeatureState.isFeatureEnabled('some_feature_flag')) {
                // do stuff
        }
    })
);

But the only way I (that I am aware of) to obtain the feature flag state is using a second select, pipe, subscribe chain, so here is what I came up with. It looks more complicated than it probably should be, and seems to be running the commented code block more than expected:

this.actions$.pipe(
    ofActionDispatched(SomeAction, takeUntil(this.onDestroy$)).subscribe(() => {
        this.store
            .select(FeatureState.isFeatureEnabled('some_feature_flag'))
            .pipe(filter(feature => feature))
            .subscribe(() => {
                // do stuff
            });
    })
);

Upvotes: 0

Views: 46

Answers (1)

martin
martin

Reputation: 96969

You can merge the two Observable into a single chain:

this.actions$
  .pipe(
    ofActionDispatched(SomeAction),
    concatMap(() => this.store
      .select(FeatureState.isFeatureEnabled('some_feature_flag'))
      .pipe(filter(feature => feature))
    ),
    takeUntil(this.onDestroy$),
  )
  .subscribe(() => {
    // do stuff
  });

Upvotes: 1

Related Questions