Help with chaining storage/observables?

Storage from @ionic/storage is an observable, which makes it a little harder to deal with. Say I want to use two values from storage, I can do this:

  let a,b;
  this.storage.get('a').then((data) => {
    a = data;
    this.storage.get('b').then((data) => {
      b = data;
      doSomething(a, b);
    });
  });

But that’s pretty ugly, and would be worse if I needed 10 items. How can I do the storage accesses in parallel and then work with the results? Or how do I chain the observables without hierarchy hell? Thanks!

I’d look at forkJoin.

2 Likes

Thanks, rapropos, it’s beautiful! Here is the solution using forkJoin:

  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/map';
  import 'rxjs/add/observable/forkJoin';    // observable not operator!!

  Observable.forkJoin(
    this.storage.get('a'),
    this.storage.get('b')
  ).subscribe(doSomething);   // function doSomething is passed an array [a,b] 

I’m sure I will learn to enjoy many more rxjs goodies as I work with Ionic 2!

1 Like