Understanding and creating observable

Reading Time: 3 minutes

In this blog, we will observe the observables by using practical implementations. So, let’s start with the understanding of the observable to the creation of the custom observable.

Here we begin!!!

What is an observable?

Observable is basically a data source, which gets imported from the package ‘rxjs’.

To understand the observable implementation, we have the observable, an observer and in between we have the timeline where we have multiple events which are made by the observable.

Let us take the example, like we have a button and when the button is clicked, an event in the data package is emitted automatically.

Ways of handling data packages

There are three ways of handling data packages:

  • Normal data
  • Handle errors
  • Handle completion

And in these three different buckets, your code gets executed which depends on the type of package you receive.

Observable is used for asynchronous tasks, better technique for event handling and handling multiple values. Like, in case of asynchronous tasks , all the data sources uses events, triggers in the code.

Example:

As HTTP request, triggers in the code, and in that case, we don’t know when the task gets executed or how long it will take to get finished. So, in case if we want to execute the normal code then, we don’t want to wait for these events/or such HTTP requests as they will block the program. Therefore, to handle all these observable is the different approach in angular.

A special feature about observable

It can be accessed by a user who subscribes to it.

Observables are the constracts to which you subscribe to be informed about the changes in data. As these are the streams of data and whenever the data is emitted then, the subscription will know about it.

Build in observable

Params: It is an observable which gives the new route parameter, new values whenever the parameter in the URL changes.

Example:

ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.id = +params.id;
});
}

In this example, we get the new params and we extract the id params from that.

Building your own observable

For this, you need to create an observable instance that defines a subscriber function.

For creating this, you need to import that from ‘rxjs’ package. So, here we are importing the interval from ‘rxjs’.

import { interval } from 'rxjs';

Now, call that interval and pass the number for the event to occur.

ngOnInit() {
 interval(1000).subscribe(count => {
console.log(count);
});

Here, one argument is passed to that subscribe i.e. count, which gives the incremental number.

Output:

When the user navigate through different links then, it gives the incremental value which leads to the memory leak, once this code run.

To prevent this memory leak you need to store that subscription. And below is the example

import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval } from 'rxjs';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy{
private firstObsSubscription: Subscription;

constructor() {
}

ngOnInit() {
this.firstObsSubscription = interval(1000).subscribe(count => {
console.log(count);
});
ngOnDestroy(): void {
this.firstObsSubscription.unsubscribe();
}
}

So, as a result we can store whatever the subscribe returns and subscribe returns the subscription.

We can now call the OnDestroy lifecycle hook which means that when we leave that component we can clear that subscription which helps to prevent the memory leak.

Observers

Observer is a part which is interested to know about errors, new data or completion of the data. For all this, we need an observable interface which consist of callback methods.

Some of the methods are:

  • next: It is use to emit new values. It can be called zero or more times once the execution gets started.
  • error: It is use to show the error messages.
  • complete: It is use to notify the completion of an observable. Example:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription, Observable } from 'rxjs';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
private firstObsSubscription: Subscription;

constructor() {
}

ngOnInit() {

const customIntervalObservable = Observable.create(observer => {
let count = 0;
setInterval(() => {
observer.next(count);
if (count === 5) {
observer.complete();
}
if (count > 3) {
observer.error(new Error('Count is greater 3!'));
}
count++;
}, 1000);
});

this.firstObsSubscription = customIntervalObservable.pipe(filter(data => {
return data > 0;
}), map((data: number) => {
return 'Round: ' + (data + 1);
})).subscribe(data => {
console.log(data);
}, error => {
console.log(error);
alert(error.message);
}, () => {
console.log('Completed!');
});
}

ngOnDestroy(): void {
this.firstObsSubscription.unsubscribe();
}
}

Output:

Conclusion:

An observable is like a function that returns a data stream, either synchronously, or asynchronously.

Thank you for reading, if you really like the blog hit the like button and to learn more, visit here

Written by 

Aanchal Agarwal is a Software Consultant at Knoldus. Her practice area is web development. She is recognized as a multi-talented, multitasker, and adaptive to the different work environments. Her hobbies include watching movies, listening to music, and traveling. She likes to read books and explore new things.