-
-
Save Thorsson/4e4adcffdfd16a0bd87c142686542506 to your computer and use it in GitHub Desktop.
RxJS observable of property value changes, given an object and property path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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