Skip to content

Instantly share code, notes, and snippets.

@Thorsson
Forked from jayphelps/ofPropertyPathChanges.js
Created February 1, 2017 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thorsson/4e4adcffdfd16a0bd87c142686542506 to your computer and use it in GitHub Desktop.
Save Thorsson/4e4adcffdfd16a0bd87c142686542506 to your computer and use it in GitHub Desktop.
RxJS observable of property value changes, given an object and property path
function isObject(value) {
// Avoid an old bug in Chrome 19-20
// See https://code.google.com/p/v8/issues/detail?id=2291
const type = typeof value;
return type === 'function' || (!!value && type === 'object');
}
function ofPropertyChanges(obj, key) {
if (isObject(obj) === false) {
return Rx.Observable.return(undefined);
}
return Rx.Observable.ofObjectChanges(obj)
.filter(change => change.name === key)
.map(({ object, name }) => object[name])
.startWith(obj[key]);
}
function ofPropertyPathChanges(obj, path) {
const parts = path.split('.');
const firstKey = parts.shift();
const subject = new Rx.BehaviorSubject();
Rx.Observable.return(obj)
.map(obj => ofPropertyChanges(obj, firstKey))
.concat(Observable.from(parts))
.reduce(
(stream, key) => stream.flatMapLatest(
obj => ofPropertyChanges(obj, key)
)
)
.concatAll()
.subscribe(subject);
return subject;
}
ofPropertyPathChanges(target, 'first.second.third')
.subscribe(function (value) {
console.log('value:', value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment