Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace callback hell with observable

RxJS github repo explains how to create observable from event or array. I know how to replace the callback hell with async or Promise, but I couldn't find an example on how to create and return observable for my functions doing async tasks.

For example,

x = getData();
y = getMoreData(x);
z = getMoreData(y);
...

getData(function(x){
    getMoreData(x, function(y){
        getMoreData(y, function(z){ 
            ...
        });
    });
});

How do I replace this callback hell with observables? I found we can call observer.next() method in RxJS github - creating observable but couldn't figure out an implementation for this example.

like image 205
Ankush Avatar asked May 22 '16 21:05

Ankush


1 Answers

you could use the flatMap operator instead to chain results. Have a look here : RxJS Promise Composition (passing data). Basically chaining promises is the same as chaining flatMap. That is :

pl().then(p2).then(p3).then(console.log);

is similar to :

 Rx.Observable.just()
         .flatMap(p1)
         .flatMap(p2)
         .flatMap(p3);

So the transition from promises to observables is simple. If you have a function which operates with a callback instead of a promise, I can think of two options :

  • Try to use Rx.Observable.fromCallback or Rx.Observable.fromNodeCallback
  • Wrap the callback in an observable of your own. Have a look here too : rx.js how to chain observables

For instance, function asyncCall (param, cb) would lead to something like :

Rx.Observable.create (function(observer){
  asyncCall(param, function cb(err, data){
    if (err) {observer.onError(err)}
    else {
      observer.onNext(x);
      // The following is supposing your callback is only called once, so there is no more data
      observer.onCompleted();
    }
  }
})

Once that's done you can use flatMap (or concatMap if order of execution matters) as shown before.

like image 197
user3743222 Avatar answered Sep 29 '22 07:09

user3743222