Reputation: 407
I'm very new to RxJs and need some help understanding how to make this work:
let myObs= Observable.fromPromise(this.storage.get('storageKeyForArray'))
.map(a=>Observable.from(a)) //does this blow up if array is null?
.map(e=>doSomethingWithElement(e)) //flatMap?
...
;
myObs.first().subscribe((initializedArray) => {
this.stuff= initializedArray;
this.initialized = true;
});
This is what i'm trying to do:
Upvotes: 2
Views: 1562
Reputation: 14687
You need something like this:
Observable.fromPromise(asyncLoadArrayOperation())
.flatMap(x => Observable.from(x))
.flatMap(x => someAsyncFunction(x))
.toArray()
.subscribe(x => ...)
flatMap(x => Observable.from(x)) - assuming x is an array, Observable.from returns an Observable that emits the items of the array one by one. The flatMap operator will flat this Observable, meaning, the next operator will get the items and not an Observable of the items (if were using 'map').
flatMap(x => someAsyncFunction(x)) - in this case the flatMap is used to get the someAsyncFunction promise execution result. Again, if you were using 'map' it would have emitted a Promise.
toArray() - this operator collects all the items until the source Observable completes, then emits one item - an array of all the items.
Upvotes: 3