Introducing Rx Concepts

First, we need to figure out where observables stand in the greater context of JavaScript land. This is a variable:

 let​ myVar = 42;

As you probably know, a variable contains a single value and that value can be used immediately after declaration. Variables are pretty simple. On the other hand, we have arrays:

 let​ myArr = [42, ​'hello world'​, ​NaN​];

This array represents a collection of values. Like the humble variable, an array also contains its data at the moment of creation. If all of programming just used these two concepts, life would be pretty easy. Everything needed to run a program would be immediately available when the program started. Unfortunately, there are times when the data the program needs isn’t immediately available. For instance, a web page might need to make an AJAX request to get information about the current user:

 let​ user = getUserFromAPI();
 doSomething(user);

Running this code results in a fireball of cataclysmic proportions or a stack trace. Either is likely (though it’s probably the stack trace). In any case, what it doesn’t get is our data, since the request has been made to the backend but hasn’t finished yet. One possible solution to this problem is to stop the entire process and do nothing until the AJAX request returns. This is silly. If my wife asks me to unload the groceries when she returns from the store, the proper answer is not to sit absolutely still on the couch until she arrives. Instead, I make a mental note that I have a task to do some time in the future. The JavaScript version of this mental note is called a promise:

 let​ userRequest = getUserFromAPI();

Like a variable, userRequest contains a single value, but it doesn’t immediately have that value. A promise represents data that has been requested but isn’t there yet. To do anything with that data, we need to unwrap the promise using the .then method:

 let​ userRequest = getUserFromAPI();
 userRequest.then(userData => {
 // Called when the request returns
  processUser(userData);
 });

Acting as a “mental note,” a promise allows the core process to go on doing things elsewhere, while the backend rustles through various database indexes looking for our user. Once the request returns, our process peeks inside the .then to see what to do, executing whatever function we passed in.

So far we’ve covered:

Sync

Async

Single

Variable

Promise

Collection

Array

???

The remaining piece in the puzzle is the topic of this book: The observable. Observables are like arrays in that they represent a collection of events, but are also like promises in that they’re asynchronous: each event in the collection arrives at some indeterminate point in the future. This is distinct from a collection of promises (like Promise.all) in that an observable can handle an arbitrary number of events, and a promise can only track one thing. An observable can be used to model clicks of a button. It represents all the clicks that will happen over the lifetime of the application, but the clicks will happen at some point in the future that we can’t predict.

 let​ myObs$ = clicksOnButton(myButton);
Joe asks:
Joe asks:
Why Is There a Dollar Sign?

You’ll notice that there’s an odd dollar sign hanging onto the end of the variable name. This is a convention in the Rx world that indicates that the variable in question is an observable. This convention is used throughout the book, and you’re encouraged to use it in your own work (though it’s by no means mandatory).

These clicks will happen over the lifetime of the application (imagine designing a web app that expects every click to happen at once!). Much like a promise, we need to unwrap our observable to access the values it contains. The observable unwrapping method is called subscribe. The function passed into subscribe is called every time the observable emits a value. (In this case, a message is logged to the console anytime the button is clicked.)

 let​ myObs$ = clicksOnButton(myButton);
 myObs$
 .subscribe(clickEvent => console.log(​'The button was clicked!'​));

One thing to note here is that observables under RxJS are lazy. This means that if there’s no subscribe call on myObs$, no click event handler is created. Observables only run when they know someone’s listening in to the data they’re emitting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.24.106