Skip to content

Instantly share code, notes, and snippets.

@xavierlepretre
Last active September 12, 2019 22:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xavierlepretre/46d6cd2a51ae7860edfe3b726a5ee097 to your computer and use it in GitHub Desktop.
Save xavierlepretre/46d6cd2a51ae7860edfe3b726a5ee097 to your computer and use it in GitHub Desktop.
Convert `web3.eth` asynchronous calls into Rx observables.
const Rx = require('rx');
module.exports = {
rxify: function (web3) {
// List synchronous functions masquerading as values.
var syncGetters = {
db: [],
eth: [ "accounts", "blockNumber", "coinbase", "gasPrice", "hashrate",
"mining", "protocolVersion", "syncing" ],
net: [ "listening", "peerCount" ],
personal: [ "listAccounts" ],
shh: [],
version: [ "ethereum", "network", "node", "whisper" ]
};
Object.keys(syncGetters).forEach(function(group) {
Object.keys(web3[group]).forEach(function (method) {
if (syncGetters[group].indexOf(method) > -1) {
// Skip
} else if (typeof web3[group][method] === "function") {
web3[group][method + "Observable"] = Rx.Observable.fromNodeCallback(web3[group][method]);
}
});
});
},
};
@xavierlepretre
Copy link
Author

xavierlepretre commented Dec 15, 2016

You use it thus:

const Web3 = require("web3");
const web3 = new Web3(...);
const Rxifier = require("./rxifyWeb3.js");
Rxifier.rxify(web3);

web3.eth.getBlockNumberObservable()
    .flatMap(web3.eth.getBlockObservable)
    .subscribe(function (block) {
        console.log(block);
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment