Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Promise to Observable

I am trying to wrap my head around observables. I love the way observables solve development and readability issues. As I read, benefits are immense.

Observables on HTTP and collections seem to be straight forward. How can I convert something like this to observable pattern.

This is from my service component, to provide authentication. I'd prefer this to work like other HTTP services in Angular2 - with support for data, error and completion handlers.

firebase.auth().createUserWithEmailAndPassword(email, password)   .then(function(firebaseUser) {     // do something to update your UI component     // pass user object to UI component   })   .catch(function(error) {     // Handle Errors here.     var errorCode = error.code;     var errorMessage = error.message;     // ...   }); 

Any help here would be much appreciated. The only alternative solution I had was to create EventEmitters. But I guess that's a terrible way to do things in services section

like image 589
Krishnan Sriram Avatar asked Sep 04 '16 16:09

Krishnan Sriram


People also ask

Can Promise be converted to Observable?

The correct pattern to transform a promise into an observable is using defer and from operators: import { defer, from } from 'rxjs'; const observable$ = defer(() => from(myPromise())); Why we need the defer operator? Promises are eager, this means that when called they fire instantly.

How do you make an Observable Promise?

To convert a promise to an observable with Rxjs, we can use the from function. import { from } from "rxjs"; //... const observable = from(promise);

How do you use Observable instead of Promise?

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.


2 Answers

If you are using RxJS 6.0.0:

import { from } from 'rxjs'; const observable = from(promise); 
like image 116
Guillaume Avatar answered Oct 10 '22 13:10

Guillaume


try this:

import 'rxjs/add/observable/fromPromise'; import { Observable } from "rxjs/Observable";  const subscription = Observable.fromPromise(     firebase.auth().createUserWithEmailAndPassword(email, password) ); subscription.subscribe(firebaseUser => /* Do anything with data received */,                        error => /* Handle error here */); 

you can find complete reference to fromPromise operator here.

like image 39
Godfather Avatar answered Oct 10 '22 12:10

Godfather