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);
oplete();
});
});
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.plete();
});
});
Share
Improve this question
edited Feb 20, 2018 at 2:36
Adam Kipnis
11k10 gold badges40 silver badges51 bronze badges
asked Feb 20, 2018 at 0:32
Nazar KalytiukNazar Kalytiuk
1,7792 gold badges15 silver badges23 bronze badges
3
-
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 Commented Feb 20, 2018 at 0: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 Commented Feb 20, 2018 at 1:02 -
It's usually a good idea to use the built-in observable creators wherever possible. Look at
bindNodeCallback
. – cartant Commented Feb 20, 2018 at 1:15
1 Answer
Reset to default 8RxJS 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.