Search code examples
angulartypescriptrxjspublish-subscribe

RxJs: Is it correct to use try/catch into subscribe()?


Let's assume that we have angular 2 application. Some service method return data via post(), where we have catch() to catch possible errors.

In component we have subscribed on the Observable's data:

  .subscribe(
              ()=> {
                      // some code
                   } 
             )

let's assume that I try to get some data from locaStorage or any another critical operation. Can I add try/catch statement inside such method ? Or is there another correct approach ?


Solution

  • subscribe does give you options to pass in onNext and onError, but using subscribe for all side-effects isn't the best option. The whole point of Rx is to provide operators (such as catch, retry etc) to handle situations in a reactive fashion, and not simply use subscribe as a way to invoke callbacks.