Henry Henry - 10 months ago 60
Node.js Question

RxJS de-nesting callbacks

I want to do something like:

next: result => useResult(result),
error: error => handleError(error)

What I'm trying to avoid is a callback mess. In my code, functions like
are Observables, and I want to chain them. Is this pattern on the right track? Because right now as soon as one of them internally does
observer.error(new Error('problem'))
, the chain crashes and my error handler is not called. How can I improve this?

Answer Source

I think the error does propagate to your subscriptions. This should simulate your situation:

const Rx = require('rxjs/Rx');
const Observable = Rx.Observable;

let userToken = Observable.of(42);
let verifyToken = Observable.range(1,3);
let getUserInformation = Observable.of('whatever');
let createUser = Observable.create(observer => {
    observer.error(new Error('problem'));

    .flatMap(val => verifyToken)
    .flatMap(val => getUserInformation)
    .flatMap(val => createUser)
        next: result => console.log("Next:", result),
        error: error => console.log("Error subscriber:", error.message)

The output in console is as expected:

Error subscriber: problem