Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading