In the context of an Angular component I have 2 observables.
Requirements
- I want to execute both in sequence.
- If the first observable fails I don’t want to run the second
- If either fail, I want to log a single error msg
- If both succeed, I want to log a single success msg
Approach
- I am using concat to achieve #1 and #2
- I am capturing #3 in the error notification of the concat subscription. There will only ever be 1 error notification to process due to concat
- #4 is where the problem lies. I cannot use next on the concat subscription as it will log a success msg per observable. I can handle this in the complete notification of the concat subscription but that is not typically where you would handle success. There’s a code smell off this approach.
What is the best way to achieve my requirements?
getData1$ = this.myService.getData1();
getData2$ = this.myService.getData2();
constructor(private myService: MyService) {
this.getAllData();
}
getAllData() {
concat(this.getData1$, this.getData2$)
.pipe(finalize(() => console.log('always called')))
.subscribe(() => {
error: console.log('one or more data fetches have had an error');
complete: console.log('all data fetches have succeeded');
});}