Created
August 12, 2021 13:03
-
-
Save umar-muneer/56836bbf79e0d8d6349c18bd7b4cd5b9 to your computer and use it in GitHub Desktop.
Keep the Observable alive after error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Component { | |
constructor(private service: Service) {} | |
handleClick$ = new Subject(); | |
ngOnInit() { | |
this.handleClick$.pipe( | |
switchMap(() => { | |
return this.service.someObservable$; | |
}) | |
).subscribe(console.log); | |
// this observable would stop firing as soon as there is an error, subsequent button clicks will not trigger it. | |
} | |
handleClick() { | |
this.handleClick$.next(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
How to keep an observable alive even if an inner observable has errored out. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {interval} from 'rxjs'; | |
export class Service { | |
public someObservable$: Observable<number>; | |
constructor() { | |
someObservable$ = interval(1000).pipe( | |
map((x: number) => { | |
if (x === 10) { | |
throw new Error('oops!'); | |
} | |
return x; | |
}), | |
take(20) | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Component { | |
constructor(private service: Service) {} | |
handleClick$ = new Subject(); | |
ngOnInit() { | |
const someObservable$ = this.service.someObservable$.pipe( | |
catchError((error) => { | |
return of(null); | |
}) | |
) | |
this.handleClick$.pipe( | |
switchMap(() => { | |
return someObservable$; | |
}) | |
).subscribe(console.log); | |
// this observable would not stop firing as soon as there is an error, subsequent button clicks will not trigger it. | |
} | |
handleClick() { | |
this.handleClick$.next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment