What is the difference between Promise
and Observable
in Angular?
An example on each would be helpful in understanding both the cases. In w
Even though this answer is late, i have summarized the differences below,
Observable:
function
that takes an observer
and returns a function Observer: an object with next, error.
subscribe/unsubscribe
to its data stream, emit
next value to the observer, notify
the observer about errors
and
inform the observer about the stream completion
function to handle next value
,errors and
end of stream(ui events,http responses,data with web sockets).multiple values
over timecancel-able/retry-able
and supports operators such as map,filter,reduce
etc.Observable.create()
- returns Observable that can invoke methods on
-Observer Observable.from()
- converts an array or iterable into
-Observable Observable.fromEvent()
- converts an event into Observable
-Observable.fromPromise()
- converts a Promise into Observable
-Observable.range()
- returns a sequence of integers in the specified rangePromise:
A promise represents a task that will finish in the future;
Promises become resolved by a value
;
Promises get rejected by exceptions;
Not cancellable
and it returns a single value
A promise expose a function (then)
-then returns a new promise
;
-allows for the attachment
of that will be executed based on
state
;
-handlers
are guaranteed
to execute in order attached
;