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.
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 :
Rx.Observable.fromCallback
or Rx.Observable.fromNodeCallback
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With