Andreas
Andreas

Reputation: 692

Observable vs Promise for single values

Typescript (and now also ECMAScript 2017) gives you great asynchronous tools to use in the form of async/await. However, working with Angular 4, I get the feeling that using Observables is preferred. My question is: When I have a function which returns a single value once (ex: confirmation modal), are there any big advantages with using observables, or would promises (async/await) be preferred/just as good? Is it not weird to use observables? Do they not represent a stream of values?

Tl;dr:

async showDialog(msg: string): Promise<DialogResult>

vs.

showDialog(msg: string): Observable<DialogResult>

Upvotes: 4

Views: 1642

Answers (1)

martin
martin

Reputation: 96891

It doesn't matter which one you use. Promises and Observables can be freely interchanged. Have a look at this https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875

I personally find it easier to work with Observables even when you need to return just one value.

With Promises you often need to keep three properties:

class Whatever {
  resolve: Function;
  reject: Function;
  promise = new Promise((resolve, reject) => {
    this.resolve = resolve;
    this.reject = reject;
  });    

  method() {
    return this.promise;
  }

  otherMethod() {
    this.resolve();
  }
}

With Observables you can keep just an instance of Subject:

class Whatever {
  subject = new Subject();

  method() {
    return this.subject.toPromise();
  }

  otherMethod() {
    this.subject.next(...);
    this.subject.complete();
  }
}

Upvotes: 1

Related Questions