Vue.js 2 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

What is RxJS?

If we look at the RxJS documentation, we're greeted with the following definition: "ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences" (http://reactivex.io/intro.html). At first glance, this is not exactly a description that makes us feel comfortable using this within our projects.

RxJS assists us in using reactive programming principles inside of our application, often referred to as a more declarative style rather than imperative. When we talk about an imperative programming style, we're usually telling the computer the exact steps of how to do a particular task. A declarative style allows us to focus more on the expected outcome rather than the implementation.

In JavaScript, we can create an event stream by using the following:

document.addEventListener('click', event => {
console.log(event);
});

This then allows us to observe any mouse clicks on the document. We can capture things such as the click coordinates, target, event type, and so on. Evidently, this is an asynchronous observable data stream. We don't know when someone is going to click the screen, nor do we care. All we do is observe and perform a particular action when that event occurs.

We can use RxJS to take these same principles and apply it to our modern day applications where everything is a stream. We could have an observable data stream of everything from a Facebook feed to document click events, timers, anything! Everything can be a stream.