Search code examples
angularecmascript-6promiserxjsobservable

When to use Promise over observable?


Is there any case, where Promise is more powerful as compare to observable? I know a lot of benefits of observables over promises. But Is there any case, I should use only promises over observables.

I found this link, promises vs observables. But this always shows me the benefits of observables over promises. I want to know the benefits of promise over observables.


Solution

  • An observable does everything that a promise does and more. It can always be switched to a promise in case one is expected with toPromise() method (firstValueFrom and lastValueFrom in RxJS 7).

    An observable must be chosen over a promise if

    • any features that are intrinsic to observables and not promises and explained in detail in related question is in demand (notably unsubscription, incomplete observables and observables that receive multiple values)
    • API that consumes it expects an observable and doesn't use Observable.from(...) safety structure to unify observables and promises

    An observable may be chosen over a promise if the code where it's used uses observables exclusively.

    A promise must be chosen over an observable if API that consumes it expects a promise and doesn't use Observable.from(...) safety structure.

    A promise may be chosen over an observable if

    • the code where it's used uses promises exclusively (notably async functions)
    • it needs to be asynchronous by design
    • it needs to be immediately subscribed and chained then, because a chain should be broken in observables let observable = ...; observable.subscribe(...); return observable (this also requires multiple subscriptions to be tracked in case an observable is cancellable)