Reputation: 463
I have just learned not to nest subscribes, so instead I am using switchMapTo as a means of starting each successive step on the completion of the previous step:
e.g.
const s1$ = this.retrieveAnnualLeaveVariables();
const s2$ = s1$.switchMapTo(this.initialise());
const s3$ = s2$.switchMapTo(this.retrieveData());
const s4$ = s3$.switchMapTo(this.accumulateAnnualLeaveRecords());
s4$.subscribe(() => outerStream.next(someResults) ) // pass the results to the outerStream
What I am unclear about now, is how to integrate error handling in a concise manner, so that I can send an error signal to outerStream in the event of a problem, encountered anywhere within the chain.
I have tried attaching the following to the first
.catch(e => {
return Observable.of<any>([]);
});
However:
should I append this to every switchMapTo? or can I manage it in one place?
what purpose does return Observable.of([]); serve - do I call the error method on my outerStream from here?
I haven't figured out how to stop the chain of events as soon as one throws an error - how do I do that?
Thanks for any assistance!
Upvotes: 3
Views: 3309
Reputation: 718
First you should chain the operators on your observable instead of creating a new constant each time you call switchMapTo
. Then you get this.
this.retrieveAnnualLeaveVariables()
.switchMapTo(this.initialise())
.switchMapTo(this.retrieveData())
.switchMapTo(this.accumulateAnnualLeaveRecords())
.subscribe(() => outerStream.next(someResults))
Then if you have this you can add the catch
before the subscribe.
In the catch
you can either return a new "fallback" value as observable, an empty observable or throw another error.
If you want to stop the chain then you should return an empty Observable via Observable.empty()
. If you return this the Observable will complete without calling the given subscribe function.
Result:
this.retrieveAnnualLeaveVariables()
.switchMapTo(this.initialise())
.switchMapTo(this.retrieveData())
.switchMapTo(this.accumulateAnnualLeaveRecords())
.catch(() => Observable.empty())
.subscribe(() => outerStream.next(someResults))
Upvotes: 1