How to make Observable from callback
Asked Answered
D

1

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();
    });
});
Doyon answered 20/2, 2018 at 0:32 Comment(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()Stiver
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).Minnesinger
It's usually a good idea to use the built-in observable creators wherever possible. Look at bindNodeCallback.Leann
L
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.

Leann answered 20/2, 2018 at 5:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.