5

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.

Community
  • 1
  • 1
Ankush
  • 645
  • 1
  • 13
  • 28

1 Answers1

5

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.

Community
  • 1
  • 1
user3743222
  • 16,984
  • 5
  • 62
  • 71
  • so I've to pass observer in each function and it has to call observer.onNext() when it finishes, isn't it making callback hell more complicated if we just have 2-4 callbacks? – Ankush May 23 '16 at 19:56
  • I don't understand what you mean. – user3743222 May 23 '16 at 20:51
  • 1
    You are not alone. I understand you @Ankush. And yes, it's "Observable Hell". Async/Await is the way to go to make stuff understandable for us mere mortals. – Bernard Dec 04 '17 at 06:42