Hide splashscreen after storage is ready


#1

Hi all,

we are currently creating our first ionic 2 app. Inside the app we are saving data using the Storage module which is wrapped in an own storage provider.

Now, we want the app to wait / show the splashscreen until the storage provider signalizes that all data has been read from the storage. Therefore, we implemented a function called “readData” inside the storage provider which returns an Observable and signalizes readiness as soon as all keys have been read from the Storage.

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class StorageProvider {

  private entries: { [key: string]: any} = {};
 
  constructor(public storage: Storage) 
  {
  }

  public readData(): Observable<boolean>
  {
    return Observable.create(observer => {
      console.log('Reading from storage...');
      this.storage.forEach((value, key, index) => {
        this.entries[key] = value;
        console.log('Read key '+key+' with value '+value+' from storage.');
      });
      observer.next(true);
      observer.complete();
    });
  }
}

Inside the initializeApp method of app.components.ts (first method called in constructor) we now subscribe to the result of the readData method and afterwards hide the splashscreen:

import { Component, ViewChild } from '@angular/core';
import { Platform, MenuController, Nav } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { StorageProvider } from '../providers/storage/StorageProvider';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  // make HelloIonicPage the root (or first) page
  rootPage: any = NewsPage;

  constructor(
    public platform: Platform,
    public storage: StorageProvider
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.storage.readData().subscribe(ready => 
      {
        Splashscreen.hide();
        StatusBar.styleDefault();
      })
    });
  }

}

Well, it does not work. The splashscreen disappears but the data seems not to be loaded.

Did we understand wrong how observables work? Is there another / better way to achiece our goal?

Thanks,
Thomas


Weired concurrency issue with Storage
#2

Hi all.

meanwhile I changed the implementation a bit and I think the observables work (at least my subscriberes get notified when the member in my StorageProvider that are exported using .asObervable() are changed).

However, my main problem still persists: When the application is started, the StorageProvider has not yet finished to read from the Storage and thus the GUI is constructed as if the data was not there.

My question remains: How can I block the application, till my readData() method was processed?

Cheers,
Thomas


#3

Maybe this PR helps you https://github.com/driftyco/ionic-storage/pull/21