Justin_H
Justin_H

Reputation: 407

RxJs expand array from promise

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:

  1. load array from localstorage
  2. perform async lookup for each element of array
  3. wait for all element lookups to complete
  4. combine back into (now fully initialized) array
  5. sort the array (this can be done anytime after the first step)

Upvotes: 2

Views: 1562

Answers (1)

ZahiC
ZahiC

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

Related Questions