I am currently in the process of transforming the promises from the indexDB library 'idb' into Observables. While inserting values into the database is successful, I encounter an issue when initializing my service to retrieve values from the indexDB.
My goal is to ensure that the indexDB initialization is completed before calling the getTable functions. The initialization process is functioning as intended, but reading the values afterwards proves to be problematic.
private indexDB: IDBPDatabase<DatabaseSchemaV1>;
indexDB$ = new Subject<IDBPDatabase<DatabaseSchemaV1>>();
private initIndexDB$() {
return from(
openDB<DatabaseSchemaV1>(this.dbName, this.DB_VERSION, {
upgrade(db) {
db.createObjectStore(IndexDBTable.TABLE1);
db.createObjectStore(IndexDBTable.TABLE2);
},
})
).pipe(
map((indexDB) => {
this.indexDB$.next(indexDB);
this.indexDB = indexDB;
return this.indexDB$;
})
);
}
public getTableUserExercises$(): Observable<ExerciseTableItem[]> {
if (!this.indexDB) {
return of([]);
}
return from(
this.indexDB
.transaction(IndexDBTable.UserExercises)
.objectStore(IndexDBTable.UserExercises)
.getAll()
);
}
public getTableTrainUnits$(): Observable<TrainUnit[]> {
if (!this.indexDB) {
return of([]);
}
return from(
this.indexDB
.transaction(IndexDBTable.TrainUnit)
.objectStore(IndexDBTable.TrainUnit)
.getAll()
);
}
private getTables$() {
return combineLatest([
this.getTableUserExercises$().pipe(),
this.getTableTrainUnits$().pipe(),
]);
}
constructor() {
// this._indexDBSub = this.initIndexDB$()
// .pipe(map(() => this.getTables$()))
// .subscribe((values) =>
// console.log('In IndexDBSub after getTables: ', this.userExerciseTable)
// );
// this._getTablesSub = this.getTables$()
// .pipe(
// map((values) => {
// console.log('Arrays in getTablesSub: ', values[0], values[1]);
// })
// )
// .subscribe((what) => console.log(what));
const indexDB = this.initIndexDB$();
const trainUnits = this.getTableTrainUnits$();
indexDB.pipe(concat(trainUnits)).subscribe((x) => console.log(x));
}
Within the constructor, I have experimented with concat, mapping, and combineLatest calls from RxJS, but unfortunately, none of them have resolved the issue. However, a single observable can be called successfully by manually waiting for the indexDB:
this.getTableUserExercises$()
.subscribe((values) => console.log(values));