Take current BehaviorSubject value only when ActivatedRoute changes

Advertisements

this.draftService.getDraftConfig() returns an Observable that is stored as a BehaviorSubject in my service. How would I get the current value of the BehaviorSubject only when my ActivatedRoute params change? i.e. if the ActivatedRoute params don’t change I do not want to trigger the subscription.

    this.configSub = combineLatest([
      this.activatedRoute.params.pipe(
        map(x => x['environment'])
      ),
      this.activatedRoute.parent!.parent!.params.pipe(
        map(x => x['tableName'])
      ),
    ]).pipe(
      switchMap(([environment, tableName]) => {
        this.environment = environment;
        this.tableName = tableName;
        return this.draftService.getDraftConfig()
      }),
      take(1)
    ).subscribe(config => {
      this.config = config;
      this.initForm();
    });

>Solution :

You can use withLatestFrom pipe with the ActivatedRoute params Observable.

this.configSub = this.activatedRoute.params
  .pipe(withLatestFrom(this.draftService.GetDraftConfig())
  .subscribe(([params, config]) => {
    // Other stuff
    this.config = config;
    this.initForm();
});

This will emit a value when the params change and grab the latest value from the Observable returned from this.draftService.GetDraftConfig().

https://rxjs.dev/api/operators/withLatestFrom

Leave a ReplyCancel reply