An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
How to Use Observables with Vanilla JavaScript
No frameworks used, just pure vanilla JavaScript.
While working on a side project just for fun, I wanted to write a JavaScript script to call a REST API and eventually do some cool stuff on a webpage. It is purely vanilla JavaScript, with no fancy frameworks or even libraries being used.
First, I thought of using Promises for my calls and this was easy for me. I have done that a ton of times. However, it then hit me hard why dont I use Observables? I knew that vanilla JavaScript didnt natively support Observables. But couldnt I implement it myself? And thats what I did.
This is how I thought things through
The Observable itself would be of a new object type called Subject.
This Subject object should expose the subscribe and next functions.
subscribe should be called by observers to subscribe to the observable stream of data.
next should be called by the Subject owner to push/publish new data whenever available.
Additionally, I wanted the Subject owner to be able to know whenever no observers were interested in its data. This would enable the Subject owner to decide if he still wanted to get the data or not.
Also, the Subject owner should be able to know whenever at least one observer started being interested in its data. This would give the Subject owner more control on its data flow and any related operations.
Now back to the observer. He should be able to unsubscribe from the Subject at any time.
This leads us to a new object type called Subscription.
This Subscription object should expose an unsubscribe function.
unsubscribe should be called by the observer whenever he wants to stop listening to the data stream coming from the Subject.
Following these rules, I came up with the following implementation.
Implementation
Subscription
Note that Subscription just notifies the Subject when the unsubscribe function is called.
Subject
Somewhere in the Subject Owner
Somewhere in the Observer
Thats it, everything worked like a charm and I was proud of what I achieved.
So, the punch line is that coding in vanilla JavaScript is not always equal to writing boring code, you can make it much more fun
Hope you found reading this story as interesting as I found writing it.
This article was originally published here.
Original Link: https://dev.to/ahmedtarekhasan/how-to-use-observables-with-vanilla-javascript-p6l
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To