Skip to content

Instantly share code, notes, and snippets.

@umar-muneer
Created August 12, 2021 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umar-muneer/56836bbf79e0d8d6349c18bd7b4cd5b9 to your computer and use it in GitHub Desktop.
Save umar-muneer/56836bbf79e0d8d6349c18bd7b4cd5b9 to your computer and use it in GitHub Desktop.
Keep the Observable alive after error
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();
}
}
How to keep an observable alive even if an inner observable has errored out.
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)
)
}
}
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