Content
Handle events with Observable Operator, operator Who can be Observable Observable for HTTP requests Combine Observables
Observable I translate Vietnamese language like this for you to easily imagine. Once you turn on observable mode with a certain girl, you are in the phase of being obsessed with her, her every move you notice, she’s black you know, how many outfits a week she wears you also know. Just by hearing the footsteps, you know what shoes it is wearing today (this level is a bit terrible) and you have unconditional reflexes bursting out in your mouth “It’s raining this afternoon, my dear, bring it with you. Standard slippers”. This reflection is called subscription
Then back to the technical issue, this article doesn’t explain the Observable pattern, its main concepts, if you want to read it. This article has been written before, like the title of the article it spoils all the content and “Example to see why we should turn on Observable with a certain girl”< /p>
The mantra I want you to belong to
Reactive programming is working with asynchronous data streams
Having to explain this sentence a bit again, If what’s happening on the application is happening asynchronously, there is a very high chance that Observable will help our brothers and sisters’ lives less miserable strong>.
There are many ways and libraries to handle this asynchronous data flow, however, what’s cool about Observable is that it’s about to be standardized and included in ECMAScript. The RxJS library is being used widely and is so delicious.
Then let’s go to an example
Handle events using Observable
We have 1 button, when this button is clicked generate a random string. Written in both pure javascript ways, and using RxJS
const button = document.querySelector(“button”); const output = document.querySelector(“output”); button.addEventListener(“click”, e => )
In RxJS
const button = document.querySelector(“button”); const output = document.querySelector(“output”); Rx.Observable .fromEvent(button, “click”) .subscribe(() => )
It’s longer than writing pure javascript man . Why is it so complicated? That’s right, but now add this requirement: At every click to a multiple of 3 (3,6,9,12,…) a new string will be random
Rx.Observable .fromEvent(button, “click”) .bufferCount(3) // single line .subscribe(() => )
So what if you just write JS, needless to say it’ll be lengthy more.
Operator, operator
In the above example, .bufferCount *shows superior power** over conventional methods.
Watching: What is Observable
See also: Announcement on the Implementation of What is Doi Document Identifier
See also: What is Grip – Meaning of Grip in Vietnamese
It can be said that, we use this Observable because of what we can do with operator. In the RxJS library it has dozens of Operators to play with.
Another example, also the random string case above, now only wants to random when it is a triple click
strong> (one 3 click, not double click)
const click$ = Rx.Observable.fromEvent(button, “click”); click$.Observable .bufferWhen(() => ) .filter(events => events.length >= 3) .subscribe(() => )
Translating into human language it would look like this, in a 400ms interval, in the event stream is emitted (we are included in the events array), if this array is greater than or equal to 3, do the subscribed below subscribe
Have you fallen in love with Observables yet? I’m already satisfied.
Who can be Observable
Simple, young or old, boy or girl, if RxJS has a function (before it was .fromEvent) then we can make it subject to constant tracking.
Observable for HTTP requests
Another super power of RxJS : handles HTTP requests very smoothly
For example, fetching an album list and rendering.
const albumsApiUrl = “https://jsonplaceholder.typicode.com/albums”; Rx.Observable .ajax(albumsApiUrl) .subscribe( res => console.log(res), err => console.log(err) )
Mixing with the above example, we do the following awsome feature , click for a random list of albums
Rx.Observable .fromEvent(button, “click”) .flatMap(getAlbums) .subscribe( render, err => console.error(err) ) function getAlbums() ` ) }
The above example uses operator flatMap, one of the super classic operators of RxJS, which allows to merge 2 Observable arrays into 1
If we click continuously in a short time , there is a problem, re-rendering many times, we also can’t determine which request is resolved last. Specifically this, maybe the guy who started first will finish last, the story of the network, who knows what movie it downloads at that time that slows down the network, the guy who requests later may return to the destination first, then use When is the response to render, I want the response of the last request in the end.
You want, in the process of flirting, whoever stays until the last moment is the winner, you will eliminate those who flirt first? Such an example is also not correct, it must be the one who comes last to be the worst, put our mother first (this is unfair to you guys)
Can RxJS do that? Yes, everything already has operator, switch to switchMap, only the last response will be rendered, previous requests will be canceled
< p>


Rx.Observable . fromEvent(button, “click”) .switchMap(getAlbums) .subscribe( render, err => console.error(err) )
Combining Observables
Another use case we encountered forever. The filter function works like this: let the user enter the user id with , and select the music they want with . It’s important to only make a new request when both values have data in it, and re-render when one of them is changed.
Make the Observable first
const id$ = Rx.Observable .fromEvent(input, “input”) .map(e => e.target.value) const resource$ = Rx.Observable .fromEvent(select, “change”) .map(e => e.target.value)
We have to merge the two above into one, so that when one of them changes we get the final value of both. everything has an operator< /strong>, many, here combineLatest
Rx.Observable .combineLatest(id$, resource$) .switchMap(getResource) .subscribe(render)
Conclude
You have See how interesting using Observable is? If the answer is “Yes ❤️, love you forever”, dive into its document to study it more deeply. Or re-read my previous post.
If the answer is “No , I don’t care guys”. Then you should also treat it less badly, because in the future JS will be included as an official object, you won’t be able to run around.
Hope you guys. learned something interesting today, see you in another interesting article.
Original post published at VuiLapTrinh
<3 more hot JavaScript jobs at TopDev