1.

What is the difference between Observable and Promises?

Answer»

Observable and promises are used to execute asynchronous tasks in Ionic. For Ex: Making network calls, Checking the internet connection etc.

ObservablePromise
Computation does not start until subscription so you can run then only when you need the resultExecute IMMEDIATELY after creation
Provide multiple values over timeProvide only one
Subscribe method is used for ERROR handling which makes centralized and predictable error handlingPushes errors to the child promises
Provides chaining and subscription to handle complex applicationsUses only .then() clause
  • Example of Promise and Observable

i. Promise

var promise = new promise((resolve) => {     setTimeout(() => {         resolve(42)     }, 500)     console.log("Promise started") }) promise.then(data => console.log("OUTPUT", data))

ii. Observable

var observable = Rx.Observable.create((observer) => {     setTimeout(() => {         observer.onNext(42)     },200)     console.log("Observer started") }) observable.forEach(x => console.log("Output is x))


Discussion

No Comment Found