Home > OS >  Is there a way to subscribe to part of BehaviorSubject value changes?
Is there a way to subscribe to part of BehaviorSubject value changes?

Time:01-19

Let's say I have a behavior subject whose value consists of an object with two properties. Is there a way to subscribe to changes on only one of the properties of the underlying value?

export interface MyObject {
  property1: string,
  property2: string
};
const subject = new BehaviorSubject<MyObject>({
  property1: 'test',
  property2: 'test'
});
subject.next({
  property1: 'test',
  property2: 'test2'
});
subject.subscribe(value => {
  // how to only fire for changes on property2?
});

CodePudding user response:

You can use the distinctUntilChanged operator, and pass in a function which describes what counts as equal. If two successive values are equal, the second one gets filtered out:

subject.pipe(
  distinctUntilChanged((prev, curr) => prev.property2 === curr.property2)
).subscribe(value => {
  // do stuff
})

Equivalently, you could use distinctUntilKeyChanged:

subject.pipe(
  distinctUntilKeyChanged('property2')
).subscribe(value => {
  // do stuff
})

The above examples will still output the entire object. If you only want to output property 2, you could instead map to that, and again use distinctUntilChanged, though you won't need a custom equality function

subject.pipe(
  map(value => value.property2),
  distinctUntilChanged(),
).subscribe(property2 => {
  // do stuff
})

CodePudding user response:

You could use distinctUntilKeyChanged like this:

const source = subject.pipe(
    distinctUntilKeyChanged('property2')
);

source.subscribe();

Here source will only emit when property2 has changed since the previous emission.

  • Related