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));
As soon as we run the above code snippet, as expected the list is displayed.
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));
We use from
operator to convert our list array to an observable and can achieve the same result.
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";
interval(1000)
.pipe(take(6))
.subscribe((x) => console.log("Next: ", x));
When we run this now, you'll see they come in over time.
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)