What are Observables in Angular?

What are asynchronous operations and asynchronous data?

  • Using Observables
  • Using Promises

What is the difference between Promises and Observables?

  1. Helps you run functions asynchronously, and use their return values (or exceptions), but only once when executed.
  2. Not lazy.
  3. Not cancellable (there are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far). The two possible decisions are Reject and Resolve.
  4. Cannot be retried (Promises should have access to the original function that returned the promise to have a retry capability, which is a bad practice)
  5. Provided by JavaScript language.
  1. Helps you run functions asynchronously, and use their return values in a continuous sequence (multiple times) when executed.
  2. By default, it is lazy as it emits values when time progresses.
  3. Has a lot of operators which simplifies the coding effort.
  4. One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used.
  5. Not a native feature of Angular or JavaScript. Provide by another JavaScript library which is called Rxjs.
  • Observable — Stream of Data
  • Observer — Which is going to use the data
  • next
  • error
  • complete
this.myObservable.subscribe(next, error, complete);
import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'my-app';
myObservable = new Observable((observer) => {
console.log('Observable Starts');
observer.next('1');
observer.next('2');
observer.next('3');
observer.next('4');
observer.next('5');
});
ngOnInit(): void {
this.myObservable.subscribe((val) =>{
console.log(val);
});
}
}
myObservable = new Observable((observer) => {
console.log('Observable Starts');
setTimeout(() => {
observer.next('1');
}, 1000);
setTimeout(() => {
observer.next('2');
}, 2000);
setTimeout(() => {
observer.next('3');
}, 3000);
setTimeout(() => {
observer.next('4');
}, 4000);
setTimeout(() => {
observer.next('5');
}, 5000);
});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kasun Dissanayake

Kasun Dissanayake

Software Engineer at IFS R & D International (Pvt) Ltd || Former Software Engineer at Pearson Lanka || Former Associate Software Engineer at hSenid Mobile