'subscriber.next() is not firing after subscriber.error statement
Based on the input data I want to decide whether it is valid data or not and send the observable to the to end.
I have tried to create a observable and sequential subscribe.next() is working correctly but any error is coming then after that no statement is working.
const observable = new Observable((subscriber) => {
subscriber.next(1);
subscriber.next(2);
subscriber.error('failed this after second');
subscriber.next(3);
subscriber.next(4);
subscriber.complete();
});
observable.subscribe({
next(x) {
console.log('got value ' + x);
},
error(err) {
console.error('something wrong occurred: ' + err);
},
complete() {
console.log('done');
},
});
Current output:
- got value 1
- got value 2
- something wrong occurred: failed this after second
Expected output
- got value 1
- got value 2
- something wrong occurred: failed this after second
- got value 3
- got value 4
- done
Here is the stackblitz link https://stackblitz.com/edit/zlksm5?devtoolsheight=50&file=index.ts
help me to solve this or any alternative way to handle this scenario. I tried to find the solution but didn't get the exact answer.
Solution 1:[1]
I don't think it's possible with an Observable, cause the observable will be closed if any error occurred.
I have tried couple of ways, putting it for reference
//interval(1000)
observable
//.pipe(switchMap(() => observable))
.pipe(
catchError((d) => {
observable.subscribe((nd) => {
console.log('--again--', nd);
});
return of(d);
})
//retry(1)
)
.subscribe({
next(x) {
console.log('got value ' + x);
},
error(err) {
console.error('something wrong occurred: ' + err);
},
complete() {
console.log('done');
},
});
// interval(1000)
// .pipe(switchMap(_ => observable))
// .pipe(
// catchError((d) => {return of(d)}),
// switchMap(_ => observable)
// )
// .subscribe(d => {
// console.log(d)
// })
For your use case it's better to use a behavior subject instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dibyanshu Banerjee |