What are Observables:-
Observables are similar to promises but with major differences that make them better.
Observables | Promise |
---|---|
Observables handle multiple values over time | Promises are only called once and will return a single value |
Observables are cancellable | Promises are not cancellable |
The ability of observables being able to handle multiple values over time makes them a good candidate for working with real-time data, events and any sort of stream you can think of.
Being able to cancel observables gives better control when working with in-flow of values from a stream. The common example is the auto-complete widget which sends a request for every key-stroke.
If you are searching forangular
in an auto-complete, the first request is witha
and thenan
. The scary thing is thatan
might come back with a response beforea
which produces a messy data. With observables, you have better control to hook in and cancela
's becausean
is coming through.
Observables is an ES7 feature which means you need to make use of an external library to use it today.RxJSis a good one. RxJS also provides Observable operators which you can use to manipulate the data being emitted. Some of these operators are:
- Map
- Filter
- Take
- Skip
- Debounce