Henry Henry - 10 days ago 4
Node.js Question

RxJS de-nesting callbacks

I want to do something like:

Rx.Observable.of(userToken)
.flatMap(verifyToken)
.flatMap(getUserInformation)
.flatMap(createUser)
.flatMap(signNewToken)
.subcribe({
next: result => useResult(result),
error: error => handleError(error)
})


What I'm trying to avoid is a callback mess. In my code, functions like
verifyToken
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

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'));
});

Observable.of(userToken)
    .flatMap(val => verifyToken)
    .flatMap(val => getUserInformation)
    .flatMap(val => createUser)
    .subscribe({
        next: result => console.log("Next:", result),
        error: error => console.log("Error subscriber:", error.message)
    });

The output in console is as expected:

Error subscriber: problem
Comments