I'd like to use angular-rx for a simple refresh button for results. If the user clicks the refresh button the results are reloaded. If the user clicks the the refresh button 100times in 1 second, only the latest results are loaded. If the results failed for some reason, that doesn't mean the refresh button should stop working.
To achieve the last point I'd like to keep a subscription (or resubscribe) even if it fails, but I can not work out how to do that?
This doesn't work, but here's a simple example where I try resubscribing on error:
var refreshObs = $scope.$createObservableFunction('refresh');
var doSubscribe = function () {
refreshObs
.select(function (x, idx, obs) {
// get the results.
// in here might throw an exception
})
.switch()
.subscribe(
function (x) { /*show the results*/ }, // on next
function (err) { // on error
doSubscribe(); // re-subscribe
},
function () { } // on complete
);
};
doSubscribe();
I figure this is common enough there should be some standard practice to achieve this?
UPDATE
Using the suggested solution, this is what I've made to test:
// using angularjs and the rx.lite.js library
var testCount = 0;
var obsSubject = new rx.Subject(); // note. rx is injected but is really Rx
$scope.refreshButton = function () { // click runs this
obsSubject.onNext();
};
obsSubject.map(function () {
testCount++;
if (testCount % 2 === 0) {
throw new Error("something to catch");
}
return 1;
})
.catch(function (e) {
return rx.Observable.return(1);
})
.subscribe(
function (x) {
// do something with results
});
And these are my test results:
- Refresh button clicked
- obsSubject.onNext() called
- map function returns 1.
- subscribe onNext is fired
- Refresh button clicked
- obsSubject.onNext() called
- map function throw error
- enters catch function
- subscribe onNext is fired
- Refresh button clicked
- obsSubject.onNext() called
- Nothing. I need to keep subscription
My understanding is that catch should keep the subscription, but my testing indicates it doesn't. Why?