Say I move my mouse on a website and every location in the path is collected and stored in an array. By the end of the visit, you have a huge array with the entire path my mouse took while I was visiting your website.
Now let's say that I have access to that data in real time, as the mouse is moving across the screen. You can see this information as a stream of data that at any given time, it tells you where my mouse is.
Now that have access to a stream of data, we just need to do something to react to this stream (aka, do something every time a new mouse movement is recorded).
To keep this simple, we will just log to the screen what the X and Y coordinates of the mouse are on the website.
In RxJS, it looks something like this:
//The *stream*
const mouseMovement$ = Rx.Observable.fromEvent(document, 'mousemove');
//The *do something with it*
mouseMovement$.subscribe(position => console.log(`(${position.cilentX}, ${position.cilentY}`));
Great! But... can't we just do this with event handlers?
Well...
document.body.addEventListener('mousemove', (event) => {
console.log(`(${event.clientX}, ${event.clientY})`);
})
In this simple case, yeah - and it's quite simple too... But then what if we want to modify the information before we handle it:
//I want the distance from the center of the page
const mouseMovement$ = Rx.Observable
.fromEvent(document, 'mousemove')
.map( event => {
const posX = event.clientX - document.body.clientWidth/2;
const posY = event.clientY - document.body.clientHeight/2;
return Math.sqrt(posX*posX + posY*posY);
});
//The *do something with it*
mouseMovement$.subscribe(radius => console.log(`Radius: ${radius}`));
Or want to limit how often we get information from the stream:
//I want to know where the mouse pointer is 2.5 seconds and not more often than that
const mouseMovement$ = Rx.Observable
.fromEvent(document, 'mousemove')
.debounceTime(2500);
//The *do something with it*
mouseMovement$.subscribe(position => console.log(`(${position.cilentX}, ${position.cilentY}`));
RxJS makes is easy to do actions over time over the information we get at different points in time. When we see everything as a stream of data we want to do something with over time, RxJS starts to make more and more sense.
In my next post, we will make a typeahead using RxJS! Since I am writing this as I am learning it, the post will be with some mistakes I make in the process. Oh hey here is the post!
Thank you Toolsday podcast for the inspiration and davidkpiano for the help!
Top comments (1)
From simple to complex and all points between, you've got to love RxJS