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

Advertisements

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?
});

>Solution :

You can use the distinctUntilChanged operator, and pass in a function which describes what counts as equal:

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
})

Leave a ReplyCancel reply