Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert callback to RX.Observable in Nodejs

Tags:

node.js

rxjs

I am working on a project that is using a third-party library that cannot be swapped out. It essentially goes out to a URL source and returns data. It does not return a promise. It passes the returned data back to an anonymous callback...Not one you pass to the function.

The documentation is spotty, but here is how they instruct you to use their library.

third-party(URLsource, selector, scope)(function(err, data){ /* work with data array here*/ });

Currently, the code is a mess. This is partly do to callback hell, and over-use of promises.

Piping the data through observables would help streamline and clean up this project a lot....But I'm still learning RXjs and just how observables work.

I thought this problem would be a good candidate for:

let datapull = Rx.Observable.bindNodeCallback(third-party);
let result = datapull(URLsource, selector, scope);
result.subscribe(result => console.log(result), e => console.log("Error: " + e)

However, this doesn't work because the last parameter of:

third-party(URLsource, selector, scope)

is not callback function.

How do I wrap the results from this third-party function in an RX Observable?

like image 206
calbear47 Avatar asked Sep 25 '16 23:09

calbear47


1 Answers

Your usage example suggests that the third-party API function returns a function that takes a callback.

If that's the case, it's the result of the third-party call that needs to be passed to bindNodeCallback, not the function itself:

let datapull = Rx.Observable.bindNodeCallback(thirdParty(URLsource, selector, scope));
let result = datapull();
result.subscribe(result => console.log(result), e => console.log("Error: " + e)
like image 76
cartant Avatar answered Oct 27 '22 05:10

cartant