DEV Community

Cover image for What is an observable?
Joel Jose
Joel Jose

Posted on

What is an observable?

Introduction

Observable…….. yes its one of the most popular term that you will come across often, especially if you are an angular developer. Its a simple and powerful concept that gives a developer the power to execute asynchronous operations. In this article lets learn about what an observable is, its uses and some basic operations using an observable.

What is an observable?

Observable is a very powerful and efficient class provided by the RxJS library which helps in handling the asynchronous functions and data streams. It is a reactive approach to combine, transform, manage and manipulate streams of data.

Any continuous stream of data can be declared as an observable and the user can subscribe to it and monitor the changes in the data that is subscribed to. In simple terms we can say that observable is something that we can observe the changes constantly and in real time.

Creating my first observable

Now lets see how an observable is created.

import { Observable } from 'rxjs';
const observeMe = new Observable(observer => {
    setTimeout(() => {
    observer.next('Hello Guys');
    }, 2000);
    setTimeout(() => {
    observer.next('Hello Again');
    }, 4000);
});

observeMe.subscribe(value => console.log(value));
Enter fullscreen mode Exit fullscreen mode

In this code observeMe is variable that is initialized with the constructor of Observable.

The next() function emits a value to the observer.
When we use subscribe() on observeMe, the observable starts listening and results in the following output

Hello Guys // After 2 seconds
Hello Again // After 4 seconds
Enter fullscreen mode Exit fullscreen mode

Other operators on observable

Now lets see how of() operator is used

import { of } from 'rxjs';

const numberObservable = of(1, 2, 3, 4);

numberObservable.subscribe(value => console.log(value));
Enter fullscreen mode Exit fullscreen mode

Here the of() operator is used to convert a the fixed set of values into an observable by emitting them one by one. After converting the values into an observable, we can subscribe to it

Next is the map() operator

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

const numberObservable = of(1, 2, 3, 4);

const squaredObservable = numberObservable.pipe(
  map(value => value * value)
);

squaredObservable.subscribe(result => console.log(result));

Enter fullscreen mode Exit fullscreen mode

Here the map() operator transforms the items emitted by an observable after applying the modification mentioned.

You must also have seen the pipe() method used in the code. It has a simple task of modifying the data stream by sequentially applying the specified operators within it.

Output:

1
4
9
16
Enter fullscreen mode Exit fullscreen mode

Next is the filter() operator

import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';

const numberObservable = of(1, 2, 3, 4);

const oddNumberObservable = numberObservable.pipe(
  filter((value) => value % 2 !== 0)
);

oddNumberObservable.subscribe(result => console.log(result));
Enter fullscreen mode Exit fullscreen mode

In the above code, the filter() operator selectively emits only the items that satisfies the given condition.

1
3
Enter fullscreen mode Exit fullscreen mode

Subscribing to an HTTP Request

HTTP request is one of the best scenario where we can utilize the power of an observable. It takes an undefined time frame to get the response of a HTTP request. By subscribing to the HTTP call we can keep on listening to the call without hindering any of the other program flow and also handle the data streams seamlessly over time.

Example:

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getData() {
  this.http.get('/api/url').subscribe((response) => {
    console.log('Response: ', response);
  });
}
Enter fullscreen mode Exit fullscreen mode

In this code the subscribe() method takes a callback function as an argument that handles the emitted response from the HTTP request.

Error Handling in observable

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getData() {
  this.http.get('/api/url').subscribe((data) => {
    console.log('Data: ', data);
  },
  (error) => {
    console.log('Error: ', error);
  });
}
Enter fullscreen mode Exit fullscreen mode

Here subscribe() method takes a second callback function as an argument which handles any error that happens while listening to the observable.

Unsubscribe an observable

When we use subscribe() method to open a stream to listen to an observable it will remain open unless we unsubscribe it. It is always a best practice to unsubscribe observables in your code to prevent memory leaks and free up resources when no longer needed.

One way to unsubscribe is:

ngOnDestroy() {
    this.observable.unsubscribe();
  }
Enter fullscreen mode Exit fullscreen mode

Conclusion

This article gives the basics regarding an observable. There are a lot more to learn and explore regarding observable and RxJS library. Be sure to refer to https://rxjs.dev/guide/overview

So, that's all, guys!😉

Just keep learning!💪

Top comments (2)

Collapse
 
binoybarnabas profile image
Binoy Barnabas

Good one and simple one explanation bro

Collapse
 
ss24 profile image
._.

Thanks for this wonderful knowledge sir. A big fan of your topics.