0

I know it sounds very basic but I have big confusion about Rxjs specifically when we compare with Promises in order to fetch some data using an API. So here is a quoted defination from some xyz website:

Promise object may provide only a single value. It can be an array but it’s still a single object. On the contrary, an Observable may emit multiple values over time.

Question: My question is considering above defination, if we call an API which returns an array of numbers i.e [1,2,3,4,5], now we use either promise or observable, both will return this array response in first attempt and thats it, so what does it mean when we say Observable may emit multiple values over time?

3 Answers3

0

It means exactly what it says.

Promise

Emits one value or errors.

Observable Anatomy of an Observable

Emits multiple values over time. It stops emitting when:

  • The observable completes
  • The observable errors

Regarding your API

Does your api complete the observable after one value is emitted automatically?

  • yes it behaves the same like a promise.
  • no you have to self manage the completion, or your code will always expect your api to receive more values in the future.

Complete

You can use the take or first operator for one single emit and complete:

observable$.pipe(
  take(1)
)

Just consider this comparison to differentiate between the two operators: take vs first

Jonathan Stellwag
  • 3,843
  • 4
  • 25
  • 50
  • Thanks alot @Jonathan it really clearifies most of my confusions. One more question, how is it possible to receive any more response from an API in future? please guide or am i missing some thing? – Ahmed Murtaza Jul 22 '20 at 09:17
0

@martin shared me this answer Angular 6 - Observable explanation in plain English and that was best one and got my confusion resolved too regarding in what API based scenarios we need to implement Observables and when promises.

-1

Promises returns only a single value(group) hence if you want to return a group of records over time like promises will give you all at once while observables will call return them one at a time in an array format

Andrew
  • 105
  • 2
  • 10