Observables vs Promises
- When we work with backend services we deal with observable objects
- We use Promises and observables when working with asynchronous operations
Observables
- Observables are lazy
- Nothing happens until you subscribe to them
- They allow reactive programming
- They provide a bunch of useful operators
- Prefer observables
- You can always convert observables to promises
-
- These operators allow us to implement certain features with far less code. This is called Reactive programming
- Reactive Extensions or rxjs is the library where we get observables and operators. They allow us to write code in reactive style
- Simply create an observable and apply a bunch of operators and then we get features that are far more complex to implement in tradiontal way
- We can chain all these operators and comes to effect when we subscribe to observable
- Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change.
- RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.
Promises
- Promises are eager
- toPromise operator to convert observable to promise
- Promise has two methods "then" for getting result and "catch" for handling errors