Observable and promises are used to execute asynchronous tasks in Ionic. For Ex: Making network calls, Checking the internet connection etc.
| Observable |
Promise |
| Computation does not start until subscription so you can run then only when you need the result |
Execute immediately after creation |
| Provide multiple values over time |
Provide only one |
| Subscribe method is used for error handling which makes centralized and predictable error handling |
Pushes errors to the child promises |
| Provides chaining and subscription to handle complex applications |
Uses only .then() clause |
Example of Promise and Observable
a) Promise
var promise = new promise((resolve) => {
setTimeout(() => {
resolve(42)
}, 500)
console.log("Promise started")
})
promise.then(data => console.log("Output", data))
b)Observable
var observable = Rx.Observable.create((observer) => {
setTimeout(() => {
observer.onNext(42)
},200)
console.log("Observer started")
})
observable.forEach(x => console.log("Output is x))