Search code examples
promiserxjsobservablebluebird

Equivalent to Promise.try with Observables?


How could I start an Observable chain with a function that could potentially throw an exception and handle this exception through the observable catch mechanisms ?

Example :

createObservable(withFunctionThatThrowAnException())
            .catch( err => {})
            .subscribe(data => {})

If withFunctionThatThrowAnException throw an exception, observable chain as need been started yet and it's juste an uncaught exception, the observable.catch can't catch it.

With bluebird and Promises, I would have done :

Promise.try(() => createObservable(withFunctionThatThrowAnException()))
            .then(data => {})
            .catch(err => {})

Is there an equivalent with Observables ?


Solution

  • The direct equivalent would be defer, I guess:

    Observable.defer(() => createObservable(withFunctionThatThrowAnException()))
     .subscribe(console.log);