Search code examples
typescriptrxjsrxjs5

RXJS Subject - stopping errors from propagating


When multiple observers subscribe to an RXJS Subject, is it possible to stop an error from one observer propagating and stopping the other observers (registered later) from seeing the event

Stackblitz Example: https://stackblitz.com/edit/rxjs-cy7swm

const sub = new Subject<string>();

sub.asObservable().subscribe((val) => {
  console.log('1st sees: ' + val);
});

sub.asObservable().subscribe((val) => {
  console.log('2nd sees: ' + val);
  throw new Error('2nd throws error');
});

sub.asObservable().subscribe((val) => {
  console.log('3rd sees: ' + val);
});

sub.next('test');
sub.next('test2');

Here the 3rd observer doesn't see the event as the 2nd throws an exception, and the test2 value isn't seen by anything as the first error effectively shuts the subject down

1st sees: test
2nd sees: test
ERROR Error: 2nd throws error

Without obviously wrapping each subscribe block in a try catch, is there a better RXJS framework way of making sure that the 3rd observer still sees the value and the second call to sub.next() is observed too?

Update (as per cartant's answer):

This is better handled in rxjs6 - see updated Stackblitz with the same code, but without the side effects: https://stackblitz.com/edit/rxjs6-subject-err


Solution

  • This is a known problem with RxJS v5 and it's something that's been addressed in v6 - in which the synchronous error handling has been changed.

    In v6, what you are seeing will no longer happen. Instead, errors thrown from within 'listeners' will be rethrown asynchronously and will be seen by the application as unhandled errors.

    For more information, see this video.