Nerd For Tech
Published in

Nerd For Tech

What are Observables in Angular?

In this tutorial, I am going to explain What is Observable and Where/When we use it. We use Observable to perform asynchronous operations and handle asynchronous data. Another way of handling asynchronous is using promises. We can handle asynchronous operations using either Promises or Observables.

What are asynchronous operations and asynchronous data?

We already know that JavaScript is a single-threaded language. That means the code is executed line by line and once the execution of one code is complete then only the next code of the program will be executed. When we make a request to the HTTP server that will take more time. So the next statement after the HTTP request has to wait for the execution. It will only get executed when the HTTP request completes. We can say that the synchronized code is blocked in nature. This is the way the asynchronous programs came into the picture. Asynchronous code executing in the background without blocking the execution of the code in the main thread. Asynchronous code is non-blocking. That means we can make HTTP requests asynchronously.

Using an asynchronous program we can perform long network requests without blocking the main thread. There are 2 ways in which we can do that.

  • Using Observables
  • Using Promises

What is the difference between Promises and Observables?

Let’s say we are requesting a list of users from the server. From the browser, we are sending a request to the server and the server will get the data from the database. Let’s say the data which we are requesting is huge. In that case, the server will get some time to get the data from the database. Once the data is ready the data will send from the server to the client-side. Here server gathered all the data and when the data is ready that will send back to the client-side. This is how gets the Promise work. It promises to provide data over a period of time. Promise provides us the data once the complete data is ready. The data can be the actual data that we requested or it can also be an error. If there is no internet connection. In that case, also promises to return some data. That data will be the error message or an error object.

Observables are not waiting for the complete data to be available. An Observable streams the data. When the data is available partially it will send to the client.

Promises

  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.

Observables

  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.

An Observable is a function that converts the ordinary stream of data into an Observable stream of data. You can think of Observable as a wrapper around the Ordinary stream of data.

Rxjs(Reactive Extensions for JavaScript) is a javascript library, that allows us to work with the asynchronous data stream.

You can find everything related to Rxjs from here,

Rxjs has two main causes.

  • Observable — Stream of Data
  • Observer — Which is going to use the data

In order to make Observer use the data emitted by the Observable. For that Observer has to subscribe to the Observable.

Let’s create an Observable. To create an Observable we need to import Observable from the Rxjs library in our Angular application. When we create a new Angular project this library automatically gets installed on the project. You don’t need to install Rxjs separately.

Here I created a simple project called “my-app” and in the app.component.ts we need to import Obseravle from the Rxjs library. Then I created a new Observable object using the Observable constructor. In the constructor, we need to pass the callback function. The callback function will receive an argument which will be the Observer. This argument will be injected by the Rxjs library. This observer is the subscriber who is waiting for the data.

Inside the callback function, I am going to log a message and emit some data. To emit the data we can use observer.next(). I am going to emit 5 times data. This is the data that the observable is going to emit.

Now we need a subscription. This observable only emits the data if there is a subscriber. If there is no subscriber it will not be going to emit the data. Create a subscriber for the observable. In the ngOnInit, I am going to implement the subscriber. Subscriber takes 3 optional parameters. These 3 parameters are callback functions.

  • next
  • error
  • complete

All these 3 parameters are optional.

this.myObservable.subscribe(next, error, complete);

This next parameter which is a callback function is executed every time the next method in the observable returns a value. In this example, the “next” callback function will call 5 times because we are going to emit data 5 times. Basically, the next callback function will receive the data which the observable has returned or emitted.

Let’s go to the webpage and open the developer console. Now you can see the data emitted by the observable and it has been logged here.

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);
});
}
}

This data has been streamed one by one. Let’s emit data from a certain time interval. For that we can use setTimeout() function. I have added 1 second as the time interval.

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);
});

Now you can see the data one by one has been emitted after a certain time interval(1 second).

I hope you got a better understanding and knowledge of the Observables and the process of them in Angular. There are other ways of creating Observables and Let’s find them and learn them from the next tutorial.

Thank You!

--

--

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

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