5

Im using rxJS in Angular and have a set of Behavior Subjects that are exposed as a readonly Observable

public _data = new BehaviorSubject<DataItem[]>([]);
public readonly data$ = this._data.asObservable();

now I have noticed that if I subscribe directly to the BehaviorSubject and there is an error it will throw the error to the console.

but if I subscribe to the Observable with same error I don't get any messages and the listener is then unsubscribed automatically.

I know this is the expected behavior but...

I would like to know what is the pattern to avoid code duplication on errors e.g.

this.myDataService.data$.subscribe(d=> throwSomeError(), e=> handleError(e));
//or use this:
this.myDataService.data$.subscribe(d=> throwSomeError()).catch(e=> handleError(e));

the handleError(e)

Mortalus
  • 10,574
  • 11
  • 67
  • 117

1 Answers1

0

The second option will work better as BehaviorSubject will always kill the stream on an error.

Here's more info:

How do I throw an error on a behaviour subject and continue the stream?

Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
  • thank you but this does not answer my question .. i know that its better to use `,catch(...)` but i want the default onError in all subscibers be `console.error(...)` or `throw Error(..)` how can this be achieved while subscribing to `Observable` instead of the `BehaviorSubject ` directly – Mortalus Jun 15 '17 at 12:00
  • p.s i don't mind the stream being killed .. that not a problem i just want a good way to see errors occur in my subscriber functions... without wrinting `.catch(..)` for every subscriber.... – Mortalus Jun 15 '17 at 12:01