Convert Promise to Observable

convert promise to observable rxjs 6
convert promise to observable ionic 4
angular 8 observable from promise
make a promise an observable
observable from promise rxjs 6
observable wait for promise
convert promise to object
promise inside 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

If you are using RxJS 6.0.0:

import { from } from 'rxjs';
const observable = from(promise);

Converting a Promise into an Observable, Tagged with rxjs, promises, observables, javascript. it's a good idea to convert that promise into an observable so we can easily pipe other  The above code is the promise representation of the snippet that we want to convert to using observables in such a way that we can integrate it with other, existing, observables. This article is about a function that's returning a Promise that we'll be converting into an Observable, not just a standalone Promise.

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.

From Promises to Observables, How I switched my site from a Promises to a Reactive implementation with Observables. Tagged with rxjs, javascript, typescript, angular. A promise is a future value. An observable is a flow of past and future values. So it makes sense to convert a list of promises into an observable. Then we can do nice things on it, like.every(), which will result in a single boolean observable according to whether all the promises satisfy a given condition or not.

Direct, single execution

Use from to directly convert a previously created Promise to an Observable.

import { from } from 'rxjs';

// getPromise() will only be called once
const observable$ = from(getPromise());

The Promise's body is being executed or has already been resolved when the Observable is created. If the inner Promise has already been resolved a new Subscriber to the Observable will get its value immediately (getPromise() won't be called again).

Many functions and operators accepts Promises directly

Most RxJS functions that create Observables (e.g. merge, concat, forkJoin, combineLatest ...) and many operators (e.g. switchMap, mergeMap, concatMap, catchError ...) accept Promises directly. If you're using one of them anyway you don't have to use from to wrap a Promise first.

// Execute two promises simultaneously
forkJoin(getPromise(1), getPromise(2)).pipe(
  switchMap(([value1, value2]) => value1.getPromise(value2)) // map to nested Promise
)

Check the documentation or implementation to see if the function you're using is supporting ObservableInput or SubscribableOrPromise.

type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;
// Note the PromiseLike ----------------------------------------------------v
type SubscribableOrPromise<T> = Subscribable<T> | Subscribable<never> | PromiseLike<T> | InteropObservable<T>;
Deferred execution on every subscribe

Use defer with a Promise factory function as input to defer the creation and conversion of a Promise to an Observable.

import { defer } from 'rxjs';

// getPromise() will be called every time someone subscribes to the observable$
const observable$ = defer(() => getPromise());

The difference to from is that defer waits for a subscriber and only then creates a new Promise by calling the given Promise factory function. This is useful when you want to create an Observable but don't want the inner Promise to be executed right away. The inner Promise will only be executed when someone subscribes to the Observable. Each subscriber will also get its own new Observable.

The difference between from and defer in an example: https://stackblitz.com/edit/rxjs-6rb7vf

const getPromise = val => new Promise(resolve => {
  console.log('Promise created for', val);
  setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000);
});

// the execution of getPromise('FROM') starts here, when you create the promise inside from
const fromPromise$ = from(getPromise('FROM'));
const deferPromise$ = defer(() => getPromise('DEFER'));

fromPromise$.subscribe(console.log);
// the execution of getPromise('DEFER') starts here, when you subscribe to deferPromise$
deferPromise$.subscribe(console.log);

How to convert promises to an observable – Weapon of Choice, A promise is a future value. An observable is a flow of past and future values. So it makes sense to convert a list of promises into an observable. trying to convert swal's first promise function to observable and trying to use the cancel action. Can someone help me with the syntax pls. swal({ title: 'Are you sure?', text: "You won't be

You can also use a Subject and trigger its next() function from promise. See sample below:

Add code like below ( I used service )

class UserService {
  private createUserSubject: Subject < any > ;

  createUserWithEmailAndPassword() {
    if (this.createUserSubject) {
      return this.createUserSubject;
    } else {
      this.createUserSubject = new Subject < any > ();
      firebase.auth().createUserWithEmailAndPassword(email,
          password)
        .then(function(firebaseUser) {
          // do something to update your UI component
          // pass user object to UI component
          this.createUserSubject.next(firebaseUser);
        })
        .catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          this.createUserSubject.error(error);
          // ...
        });
    }

  }
}

Converting a Promise into an Observable, Observables and Promises serve different purposes and are good at different things, but in a specific part of an application, you will almost certainly want to. Converting a Promise into an Observable Observables and Promises serve different purposes and are good at different things, but in a specific part of an application, you will almost certainly want to be dealing with a single denomination. This means converting observables into promises and vice versa. Thanks to RxJS, this is quite simple.

angular-6-rxjs-convert-promise-to-observable, This operator can be used to convert a promise to an observable! For arrays and iterables, all contained values will be emitted as a sequence! If you want to use a Promise anywhere in an Observable chain you don't even need to convert it to Observable as it happens automatically. https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875

Turn an array, promise, or iterable into an observable., signature: toPromise() : Promise. Convert observable to promise. ⚠ toPromise is not a pipable operator, as it does not return an observable. [![Ultimate  signature: toPromise() : Promise. Convert observable to promise. ⚠ toPromise is not a pipable operator, Convert observable to promise. Examples.

toPromise, If it accepts Observable, it accepts Promise. For example, if you're using a switchMap , you can return a Promise inside of there just the same as  So let’s start off basic — why use observable at all and not rely entirely on promises? Well, that one’s easy — you can read this more detailed answer on stackoverflow but the gist of it

Comments
  • Using 6.3.3, from method returning observable but it is sending promise as value to subscriptions. :(
  • @LaxmikantDange Could you share a stackblitz that's reproducing the issue.
  • This answer is corrext for RXJS 6+. I tried to import from operators via "intuition" - I was wrong.
  • import 'rxjs/add/observable/fromPromise';
  • import { Observable } from "rxjs/Observable"; :)
  • I think that difference is capital, thanks for pointing it out.
  • Subjects are low-level machinery. Don't use subjects, except for the cases when you're extending rxjs.
  • I am just giving a solution.
  • You could have at least shown new Observable(observer => { ... observer.next() ... }) way to implement it. Even though it would be a reimplementation of existing well-known function, it would directly answer the question and wouldn't be harmful to readers.