7

I need to make observable from

window.web3.eth.getCoinbase((error, result) => { ... });

Is it a good idea?

new Observable<string>(o => {
    this.w.eth.getCoinbase((err, result) => {
        o.next(result);
        o.complete();
    });
});
Adam Kipnis
  • 10,175
  • 10
  • 35
  • 48
Nazar Kalytiuk
  • 1,499
  • 1
  • 11
  • 21
  • I'm not familiar with the first half, but you can certainly do what you are doing unless it's triggered by an event? If that is true you can use `fromEvent()` – Mike Tung Feb 20 '18 at 00:40
  • You can do this, but I’m not sure if there’s a reason to. You’re not going to get multiple values back from `getCoinbase`. The callback is only fired once (The API switched to Promise in web3 1.0.0). – Adam Kipnis Feb 20 '18 at 01:02
  • It's usually a good idea to use the built-in observable creators wherever possible. Look at [`bindNodeCallback`](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-bindNodeCallback). – cartant Feb 20 '18 at 01:15

1 Answers1

8

RxJS includes a bindNodeCallback observable creator specifically for creating observables from async functions that use Node-style callbacks.

You could use it like this:

const getCoinbaseAsObservable = Observable.bindNodeCallback(
  callback => this.w.eth.getCoinbase(callback)
);

let coinbaseObservable = getCoinbaseAsObservable();
coinbaseObservable.subscribe(
  result => { /* do something with the result */ },
  error => { /* do something with the error */ }
);

Note that an arrow function is used to ensure the getCoinbase method is called using this.w.eth as its context.

cartant
  • 57,105
  • 17
  • 163
  • 197