I am trying to cache some data using multiple Observable
s in an Ionic 3 application:
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/forkJoin'
// saves data for a single article
private saveToCache(articleId: number): Observable<any> {
this.loadingCtrl.create({ content: "Caching data. Please wait..." });
this.loadingCtrl.present();
let key = articleId;
let obs = this.articleService.getArticleFullData(key);
obs.subscribe(data => {
this.loadingCtrl.dismiss();
this.cache.saveItem("" + key, data as ArticleFullData);
this.loggingService.logInfo("Cache article: " + key);
},
err => {
this.loggingService.logError("Failed to cache data: " + key);
this.loadingCtrl.dismiss();
var toastObj = this.toastCtrl.create({ message: "Failed to cache data: ", duration: 2000 });
toastObj.present();
}
);
return obs;
}
// handler to perform caching for a list of articles
onCacheRefresh() {
// articles are not loaded for some reason
if (!this.articles)
return;
var obsArray = [];
for (let article of this.articles) {
let key = "" + article.ArticleId;
// already in cache
this.cache.getItem(key)
.then(data => {
console.log("Cache item already exists: ", data);
})
.catch(err => {
obsArray.push(this.saveToCache(article.ArticleId));
});
}
let err: boolean = false;
Observable.forkJoin(obsArray).toPromise()
.catch(err => {
if (err)
return;
err = true;
this.loggingService.logError("Failed to cache data: ", JSON.stringify(err));
var toastObj = this.toastCtrl.create({ message: "Failed to cache data: ", duration: 2000 });
toastObj.present();
});
}
If, for any reason, data fetch fails the catch
for the forkJoin
will execute for each failure. What I want is to be able to display the toast notification only once.
Question: How should I handle errors coming from multiple Observable
s?
You can try wit combineLatest operator. The syntax look like this:
const combinedProject = Rx.Observable
.combineLatest(
timerOne,
timerTwo,
timerThree,
(one, two, three) => {
return `Timer One (Proj) Latest: ${one},
Timer Two (Proj) Latest: ${two},
Timer Three (Proj) Latest: ${three}`
}
);
And you can add your catch that will be call one time if one of the observable throw an exception.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments