Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Observable from callback

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();
    });
});
like image 876
Nazar Kalytiuk Avatar asked Feb 20 '18 00:02

Nazar Kalytiuk


People also ask

How do you make an Observable?

Creating Observableslink The following example creates an Observable to emit the string 'hi' every second to a subscriber. import { Observable } from 'rxjs'; const observable = new Observable(function subscribe(subscriber) { const id = setInterval(() => { subscriber. next('hi') }, 1000); });

Is Observable asynchronous?

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous.

How many ways we can create Observable in Angular?

In Angular we can subscribe to an observable in two ways: Manner 1: We subscribe to an observable in our template using the async pipe. The benefit of this is that Angular deals with your subscription during the lifecycle of a component.

Can you subscribe to an Observable?

SubscribinglinkAn Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.


1 Answers

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.

like image 69
cartant Avatar answered Nov 15 '22 09:11

cartant