DEV Community

Cover image for What are RxJS Observables?
Nischal Dutt
Nischal Dutt

Posted on

What are RxJS Observables?

RxJS is a framework for reactive programming that makes use of Observables making it easy to write asynchronous code. Observable being a core concept in RxJS represents the idea of an invokable collection of future values or events.
Let us understand what need Observables fill and why we need them.

const list = [1, 2, 3, 4, 5, 6];

list.forEach((n) => console.log(n));
Enter fullscreen mode Exit fullscreen mode

As soon as we run the above code snippet, as expected the list is displayed.

console output

Because the array is residing in the memory, so the loop is executed instantaneously.
Now the interesting thing about this is that Observables are also collections. In fact, I can take my list array and convert it into an observable.

import { from } from "rxjs";

const list = [1, 2, 3, 4, 5, 6];

from(list).forEach((n) => console.log(n));
Enter fullscreen mode Exit fullscreen mode

We use from operator to convert our list array to an observable and can achieve the same result.

console output

Why is this interesting?
Because Observables are asynchronous. They represent a number of values over any amount of time. Or in other words, we can iterate through pretty much any data stream using Observable.
To demonstrate this asynchronous behavior, let us consider a scenario where a number is emitted every 1 second. To imitate this we can use the interval function that increments a number and emits that.

import { interval, take } from "rxjs";

  .subscribe((x) => console.log("Next: ", x));
Enter fullscreen mode Exit fullscreen mode

When we run this now, you'll see they come in over time.

async behavior using observables

The reason this is interesting is if we had a function that accepted an array, and did this to it, we could change that function to accept an observable instead and now all of a sudden, our function can handle things asynchronously.

Thank you for reading!

I hope this post was useful to you and helped you understand What are Observables and why we need them?
RxJS observable has a lot more higher-order functions such as concat, merge, map, scan, that we might find in a library like lodash making RxJS lodash for async events.

Feel free to reach out to me! 😊

💻 Github II ✨ Twitter II 💌 Email II 💡Linkedin

Top comments (0)