General Question about Observable, SQLlite, DatabaseReady in Ionic


#1

Hi everyone ,

I am working with the plugin sqlite-porter (cordova) and SQLlite to have a prepopulated DB when we are Logged on the application. I am not “relax” with Observable, so I wanted to know what do you think about this kind of implementation, if It seems good or not, and take advice anyway.

Here is my scenario :

Login Page (if not logged) => Homepage (Launch prepopulated script for db and list Item of DB).

I have so a DBProvider, with a BehaviorSubject to subscribe to Database State :

constructor(private sqlitePorter : SQLitePorter,private sqlite: SQLite, private http : HttpClient,private platform: Platform) {
 
    this.databaseReady = new BehaviorSubject(false);
    this.platform.ready().then(() => {
      this.sqlite.create({
        name: 'test.db',
        location: 'default'
      })
        .then((db: SQLiteObject) => {
          this.database = db;
			// TODO => set db filled in storage to no filled it again
            this.fillDatabase();

          })
        .catch(e => console.error(e));

  }

  fillDatabase()
  {

    this.http.get('assets/datas/nav.json').subscribe(json =>
    {
      this.sqlitePorter.importJsonToDb(this.database, json)
          .then(data => {
                this.databaseReady.next(true);
          })
          .catch(e => console.error(e));
    });
  }
  getDatabaseState() : Observable<{}> {
   return this.databaseReady.asObservable();
  }

And in A component like Home, I do :

private homeSubscriptions: Subscription;

  constructor(public navCtrl: NavController, public navParams: NavParams,private dbProvider : DatabaseProvider) {
   
  }
  public ngOnInit(): void
  {
   
    this.homeSubscriptions = this.dbProvider.getDatabaseState().subscribe(rdy => {
      if (rdy)
        this.loadCatalogs();
      }
    );
  }
  public ngOnDestroy(): void
  {
    if (this.homeSubscriptions) {
      
        console.log("unsubscribe in home");
        this.homeSubscriptions.unsubscribe();
     
    }
  }

Thanks in advance for any advice, look to this code… :slight_smile: