How to do unsubscribe when I got error in the pipeline?
I do subscribe to the subjectPipe pipeline outside doWork function.
Inside doWork function I throw an error (can be as part of my logic flow).
Everything works as expected but subjectPipe is log: "in subject error" and because I using take(1) I thought it should unsubscribe, But it does not happen because the complete function is not invoke.
How to make it unsubscribe when error happens?
The only thing I can think of is to create variable error$ and use takeUntil and then on error function to invoke error$. but I don't want to do it because is extra variable and the code will be messy if I do it for every case I have.
import { Subject, throwError } from 'rxjs';
import { map, switchMap, take, tap } from 'rxjs/operators';
console.clear();
const doWork = () => {
const subject = new Subject();
const work = () => {
throw new Error('bla');
};
const subjectPipe = subject.pipe(
tap(() => {
console.log('in subject pipeline');
}),
switchMap(() => work())
);
subjectPipe.subscribe({
next: () => console.log('in subjectPipe next'),
error: () => console.log('in subjectPipe error'),
complete: () => console.log('in subjectPipe complete'),
});
return { subject, subjectPipe };
};
const { subject, subjectPipe } = doWork();
subjectPipe
.pipe(
take(1),
tap(() => console.log('continue the pipe...'))
)
.subscribe({
next: () => console.log('in subject next'),
error: () => console.log('in subject error'),
complete: () => console.log('in subject complete'),
});
subject.next(null);