I currently have input which looks as follows
const config = {
'mainA': { sub1: { name: 'test1'}, sub2: { name: 'test2'}},
'mainB': { sub1: { name: 'test3'}, sub2: { name: 'test4'}}
};
I'm trying to write a function (createCustomObservable) which would create an observable using standard RsJS operators as follows
var observable = createCustomObservable(config);
observable.subscribe((x) => console.log(x));
The console output should read as follows
{'mainA': 'test1'} -> {'mainA': 'test2'} -> {'mainB': 'test3'} -> {'mainB': 'test4'}
A series of objects with a single propery
Does anyone have any idea how to realise this using RxJS operators? Any help would be appreciated.
The main problem for what you trying to solve is traverse the object to get all the objects that contains the "name" field, and get their value.
There's no Rx operator to automatically do that, so to achieve this task you can simply use Rx.Observable.create
- https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/create.md
const config = {
'mainA': {
sub1: {
name: 'test1'
},
sub2: {
name: 'test2'
}
},
'mainB': {
sub1: {
name: 'test3'
},
sub2: {
name: 'test4'
}
}
};
function traverse(o, func) {
for (var i in o) {
func.apply(this, [i, o[i]]);
if (o[i] !== null && typeof(o[i]) == "object") {
//going on step down in the object tree!!
traverse(o[i], func);
}
}
}
var source = Rx.Observable.create(function(observer) {
traverse(config, function(key, value) {
if (key == "name")
observer.onNext(value);
});
observer.onCompleted();
return function() {
console.log('disposed');
};
});
source.subscribe(function(next) {
console.log(next);
})
we can create a new stream by Observable constructor, You have to manually call next(), error() and complete() functions.
function createCustomObservable(config) {
return new Observable(
observer => {
try {
observer.next(config)
} catch(err) {
observer.error(err);
} finally {
observer.complete();
}
})
}
and use it this way
var observable = createCustomObservable(config);
observable.subscribe((x) => console.log(x));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.