Reputation: 103
Is there a way to use RxJS to track changes in a particular object? Based on my research, there used to be a method called Observable.ofObjectChanges() to create an observable that tracks object changes, but it looks like that has been deprecated.
I've experimented with using Object.from and Object.of but neither seem to trigger when a particular object is updated.
Any insights are appreciated!
Upvotes: 0
Views: 2430
Reputation: 1560
Wrap a BehaviourSubject with an Observable and listen to the Observable.
private _aStringArry: BehaviorSubject<string[]> = new BehaviorSubject(null);
public aStringArray: Observable<string[]> = this._aStringArry.asObservable();
setStringArray(stringArray: string[]): void {
this._aStringArry.next(stringArray);
}
Subscribe to aStringArray for changes. I suggest this as in some cases BehaviorSubjects would throw Promise rejections unless wrapped in Observables.
Upvotes: 2
Reputation: 5683
You could add a custom setter for the property you want to monitor, that notifies an RxJS BehaviorSubject, and then you subscribe to that subject to listen for changes.
Something like this:
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
class MyClass
{
changesSubject : BehaviorSubject<any> = new BehaviorSubject();
_myprop : any;
public set myprop(val : any) {
this.changesSubject.next(val);
this._myprop = val;
}
}
let myobj = new MyClass();
myobj.changesSubject.subscribe((val) => console.log(val));
myobj.myprop = "this should trigger a change detection";
Upvotes: 2