Another episode of "code this 💪, not that 💩" looking at ten important concepts in RxJS and how to avoid common anti-patterns. https://fireship.io

- Source Code https://github.com/fireship-io/175-code-this-not-that-rxjs
- ReactiveX http://reactivex.io/
- print method code https://gist.github.com/codediodeio/ed900f4cf5752b54160a82bc3ab2d9ea

#RxJS #JavaScript
2024-02-04T06:52:48.405Z
nova-2
2-general-nova
2024-01-09.29447
30089e05-99d1-4376-b32e-c263170674af
d3de4cc3-81cf-41a8-aa5c-5723123ab7b5
e4ad57765270d788ee7a23999455e8d527acdf5c6077257b3ce4f5037cc0f8f3
67875a7f-c9c4-48a0-aa55-5bdb8a91c34a
deprecated
One of the most difficult but also most rewarding JavaScript libraries to learn is RxJS.
It's a tool that helps us control data as it flows through the dimension of Time.
In today's episode of Code This Not That, you'll learn 10 fundamental concepts in RxJS and how to avoid the bad stuff.
If you're new here, like and Subscribe and leave me a comment below for a chance to win this t shirt next week.
Arc's JS is getting pretty popular these days.
In fact, it gets more daily NPM PM downloads, then Angular, React, and Vue.
And the only functional library that I'm aware of that's bigger is Lodash.
And the reason it's so popular is because JavaScript alone doesn't give us quite everything We would like to work with asynchronous streams of data.
We have promises, but they only work with a single async value.
So we use callbacks for real time streams, but you've probably heard the term callback help.
RxJS addresses these issues and gives us a powerful functional library for dealing with streams.
And when I say stream, I'm talking about any data source that unfolds over the dimension of time, Things like data from Firebase, DOM events, WebSockets, file uploads, etcetera.
The first thing you'll need to do is install RxJS.
I'm currently running version 6.4.
Now I'm just using vanilla JavaScript with Webpack, but feel free to follow along with your favorite JavaScript framework.
The most fundamental class in RxJS is the observable.
You can think of it as a wrapper for some data that can be subscribed to, and then the subscriber will be notified anytime the data changes.
When working with RxJS, you should think of yourself as a plumber.
And I mean that in the most literal sense because an observable is essentially a pipe for data and RxJS gives you all kinds of tools to modify those pipes.
Let's go ahead and create our first observable, but first we need to import the RxJS library, and there's a right and a wrong way to do this.
Currently, I'm doing it the wrong way by using import star as RX, but that's going to cause the entire library to be bundled up in our code.
You can see down here we have a bundle size of 47 kilobytes, but RxJS is a tree shakeable library, which means we only have to import the code that we actually need.
So when working with RxJS, you should only import the classes and operators that you actually need in your source code.
And by doing that, we reduce our bundle size to less than 2 kilobytes.
Now that you know that, let's go ahead and create an observable from scratch.
Now you won't normally create observables like this in your own code, but it's a good exercise to understand what an observable is.
When we call observable create, it gives us a callback function that we can use to notify a subscriber with some new data.
This can be synchronous or asynchronous.
But, basically, every time we call next, it's like emitting an event to the subscriber that they can listen to and react to.
Now that we have our observable created, we can create to that observable by calling subscribe on it.
Subscribe takes a function that will be called every time the observable emits a new value.
And this is why they call it reactive programming because with your subscription, And you're reacting to changes in the observable data.
Throughout this video, I'm using my own helper method called print, which will react to each newly emitted item and print it to the DOM so we can visualize what's happening in the observable.
And if we open this in the browser, you can see we get a b c logged 1 after the other.
Another important concept to keep in mind is that observables can be completed, which means they'll be shut off and no longer emit values.
If we had observer complete and then go back to the browser, you can see that Only a and b are emitted, and that's because the stream has been closed.
If you think like a plumber, creating the observable is like connecting a pipe to a water source And then subscribing is like opening the valve that lets that water out.
RxJS provides a bunch of helper functions that make it easier to create observables.
For example, if we want to just create an observable of a raw value, we can use of.
This will just take the value that you pass in and wrap it in an observable.
If we subscribe to this, then we'll just get hello printed out in the console.
Now the of function is very easy to mix up with the from function, which takes an array, promise, or iterable and then emits each individual item from the observable.
We can see the difference by passing in a string, which itself That's iterable.
Instead of emitting the entire string as one event, it emits each individual character in that string.
Another thing we can do is create an observable from events in the DOM.
Using from event, we first pass in a DOM element and then the event that we wanna listen to.
If we listen to clicks on the document and subscribe to the observable, we'll get an event every time we click on the page.
Another thing we can do is set up an observable based on a time interval.
It takes the number of milliseconds as its argument and then will emit a number each time that interval passes.
Now Now one thing that a lot of people don't realize is that RxJS can be synchronous or asynchronous.
And you'll probably never have to do this, but you can control that behavior by modifying schedulers.
If you get lost in this next example, I would recommend watching my async await video, which will teach you all about the event loop in JavaScript.
Let's go ahead and define a string observable using of, and then we'll just synchronously call our print method with world.
In this case, RxJS is going to treat that observable as a synchronous value.
So the subscription will happen on the main thread.
Therefore, we get hello, world printed 1 after the other.
You can change this behavior by modifying the scheduler of the observable.
If we pass in the async Scheduler, it will emit the value of the observable on the next iteration of the event loop.
This time in the browser, we get world hello.
And, again, you'll probably never need to mess with that, but I just wanna give you an idea of Schedulers do.
The next thing we'll do is look at the difference between hot and cold observables.
I don't really like this terminology, and I think the best way to think of it is observables can have multiple subscriptions whereas cold observables can only have one subscription.
Cold observables don't actually create the underlying value until they're subscribed to.
We'll go ahead and create an observable from scratch and just have it generate a random number.
Now if we subscribe to this observable twice, you'll see that we get 2 different random numbers.
That's because that create callback function isn't called until the subscription is created.
But often in the real world, that's not what you actually want.
A lot Times RxJS is valuable because you can share a value across multiple subscribers.
If you have an existing cold observable, there are multiple ways to make it hot or in other words, allow it to be broadcast to multiple subscribers.
Now in this example, only the first subscriber will get the actual value.
But what's often useful in the real world is to use the share replay operator, which will cache the last value as well.
If instead we pipe in share replay 1, you can see that both will get the same random number.
Now in my experience, I'm not usually taking cold observables and making them hot.
Instead, I'm creating subjects or behavior subjects.
You can think of a subject as a hot observable, but it has the added benefit of being able to have new values pushed to it.
In plumbing terms, it's more like a pump where you can add new values to the stream after it's been created.
We can do this easily by just instantiating a new subject, and then we can subscribe to it just like we've done with our other observables.
What's unique about it is that it has a next method that we can call to add new values to the stream.
Now a potential gotcha with a regular subject is that you need to have the subscription set up before you start adding values to it.
You can see here in this first example, we subscribe, then we add 2 new values to it, then we set up a second subscriber.
And what you intuitively might think is that both subscribers will get the same values.
But that's not true for the second subscriber, which will get nothing because it Subscribe late after the values were already added.
And that brings me to one of the most useful things in RxJS, which is the behavior subject.
It's similar to the subject we just looked at, except it has the concept of a current value.
This means the last emitted value will be cached similar to how we set it up with share replay earlier.
But most importantly, it means that every subscription will always receive a value.
Even though our second subscriber came in late, it still gets the last emitted value in the stream.
That tends to be a very powerful feature when doing things like state management and front end applications.
At this point, we've only been talking about creating observables.
Now it's time to look at operators, which help you control the Flow of data going through your observables.
There are a ton of operators built into RxJS, so we'll just look at a handful of some of the most popular ones.
First, we'll create a source observable that emits the integers 1 through 10.
You can compose multiple operators together by using a pipe.
And just like it sounds, your data will flow through this pipe and then be modified by each function or operator in the pipe.
If we subscribe to the empty pipe, it just emits the values of 1 through 10.
To take the input and simply transform it to a new output, you can use the map operator.
For example, we can take each number and then raise it to the power 2.
Now the observable emits the square of the initial numbers.
Another thing we can do is accumulate values as they flow through the observable similar to array reduce.
If we wanna keep a running total of all the values that were emitted in this observable, we can use the scan operator and then add the current value to the accumulated value.
Now each emitted value gets added on top of the previous one.
An important thing to keep in mind here is that the order of operation matters.
For example, if we move the scan operator before the map operator, we're going to Different results because the underlying math is now different.
So that's how you transform values.
But another useful operator is filter which prevents certain items from being emitted in the stream.
For example, if we only want values that are greater than 10, we can use the filter operator and that will only emit values that meet this condition.
And now we only see values that are greater than 10 printed in the UI.
Another thing we can do with operators is tell the observable to complete.
For example, if we pipe in take 3, it will only emit 3 values from this observable then complete it.
The next thing I wanna show you is an operator called tap, which allows you to trigger side effects from inside the observable pipe.
In all the examples so Far, I've been printing values to the screen by using the callback in the subscribe method, but that only gives us access to the value at the end of the pipe.
Most simple use case that you'll find is just console logging at different points within the observable pipe.
The pipe modifies things from top to bottom.
So if we add a tap to the very beginning, it's going to print the initial value.
And if we map it to something else and add another tap after that, it's going to print a different value.
And you can use tap to trigger more complex side effects.
For example, you might want to save a value from the observable to a back end database.
If you're using something like Firebase, bass, you'll probably wanna use an async function.
So basically, it just gives you a context to tap into the observable and do something.
Another term you might hear with RxJS is backpressure.
And, basically, that means you have an observable that's emitting way more values than you actually need.
We can simulate this in the code by listening to the mouse move event on the DOM.
Moving the mouse across the screen will cause the observable to emit multiple events every second.
RXJS has several operators that can help us with this situation.
The first strategy we'll look at is to debounce the events.
A debounce will filter out all events until they have stopped happening for a certain period of time, in this case, a 1000 milliseconds.
A debounce is really useful for something like a type ahead where you don't wanna make an API call until the user is done typing.
You can see here if we mouse around for a little while, nothing happens.
Then if we stop, Our event will be emitted after one second.
An alternative to a debounce is a throttle.
It will emit the first value, but make sure that no additional values can be emitted until a certain time period has passed.
We go back to the demo and start moving around, at the very most, we'll get one event emitted per second.
These operators are alleviating the back pressure, but they're also filtering out a lot of data.
If we want to keep all the data but just not listen to it all at once, we can use a buffer.
This will collect all the events into an array and then only emit them when they get to a length of 20.
Now we're going to switch gears to another very important operator called switch map.
This allows you to start with one observable and then switch to another one, which is very important when we're talking about data.
For example, if you're a Firebase user, you probably have an observable of a user logged into your app, and then you might want to switch to another observable of Some information about that user in the database.
We can simulate that in our code by creating an observable of an object, and then I'll create a function that returns an observable of Some information based on a user ID.
We can't call this function until we have a user ID.
So the question becomes, how do we get the user ID out of the observable?
The naive way to do this is to nest subscriptions within each other.
So first, we subscribe to the user.
That'll give us the user ID.
Then we create another description inside of that callback for the orders.
That code will actually work, but there's a better way to do this.
Instead, we'll start with our user observable To compose a new observable called orders, we first add a pipe to the user and then we use the switch map operator, which will give us access to the user ID.
And then we just return an observable from it, and you can also return a promise or an array here as well.
So if you ever have one value that depends on another value, switch map might be the operator that you're looking for.
But there might be other cases where you have multiple observables that you just want to combine into a single stream.
We'll look at 2 different functions here called combine latest and merge.
And keep in mind these are not technically operators, so we import them directly from RxJS.
I'm creating a cold observable of a random number then I'm creating a second observable that just adds a delay to that random number.
1st, we'll use combine latest and it takes an array of observables And it will wait for each observable to emit a value and then emit everything together as an array.
Even though the random numbers are going to emit something right away, going to wait for that delay to resolve into a value before it emits anything.
Then if any of the observables emit anything after that, it will emit everything again as an array.
In other words, it gives you the current state of every observable in this array.
So initially, it's blank for one second waiting for that delay and then it emits out the 4 random numbers.
In many cases, though, you don't want to wait for that delay.
So instead, you can use merge which will just emit each value 1 by 1 as it comes in through the stream.
Merge doesn't care about the array position of the observable.
It only cares about when it emits it in the context of time.
So it emits the first three values and then the delayed value a second later.
Another thing you might be wondering is how to catch errors in the context of a stream.
You have a lot of flexibility here, but one of the most common strategies is to catch the error and then replace it with some other value.
We can do this easily with the catch error operator.
It can intercept the error and then emit some other default value out of the stream.
And one thing that's really nice about RxJS is you can easily retry Try things by just piping in the retry operator.
I'm not going to get into it here, but it's super useful when working with HTTP calls.
1st, I'll push a regular value and then an error to the subject.
If we don't catch the error, we'll get this uncaught error in the console.
But by using the catch error operator, we can handle it in the background and then provide some useful information to the user in the front end.
Now if you're a good plumber, then you shouldn't have pipes that leak.
And by that, I'm talking about memory leaks.
There are 2 main ways to prevent memory leaks with RxJS.
The first way is to unsubscribe from your subscriptions.
Take, for example, this interval.
This interval is going to run forever.
So if we don't close the subscription, it's just going to create a memory leak in the background.
One potential way to handle this is to create a variable for the subscription and then call subscription unsubscribe at some other point in the code.
This will stop the leak because we can see here the observable only emits 10 values, but there's actually a better way we can do this.
We can pipe in the take while operator to the interval itself And that will tell it to emit values only while a certain condition is true.
When that condition becomes false, it will stop emitting values, therefore, preventing the memory leak.
And we don't need to manually unsubscribe anywhere in our code.
That works well in a lot of situations, but sometimes you want some other observable or subject to be the thing that triggers the subscription to stop.
For that, we have the take and tell operator and it takes an observable as its argument.
And when that observable emits something, it will cancel the subscription on the source.
For example, if we wanted to set a timer for 2 2nd on this interval, we could do that by using take and tell with a timer observable.
When the timer finishes it will complete the interval and then end the subscription.
Gonna go ahead and wrap things up there.
We barely just scratched the surface with RXJS, so let me know what you wanna see next in the comments.
If this video helped you, please like and subscribe.
Thanks for watching and I will talk to you soon.

Speaker 0: One of the most difficult but also most rewarding JavaScript libraries to learn is RxJS. It's a tool that helps us control data as it flows through the dimension of Time. In today's episode of Code This Not That, you'll learn 10 fundamental concepts in RxJS and how to avoid the bad stuff. If you're new here, like and Subscribe and leave me a comment below for a chance to win this t shirt next week. Arc's JS is getting pretty popular these days.

In fact, it gets more daily NPM PM downloads, then Angular, React, and Vue. And the only functional library that I'm aware of that's bigger is Lodash. And the reason it's so popular is because JavaScript alone doesn't give us quite everything We would like to work with asynchronous streams of data. We have promises, but they only work with a single async value. So we use callbacks for real time streams, but you've probably heard the term callback help.

RxJS addresses these issues and gives us a powerful functional library for dealing with streams. And when I say stream, I'm talking about any data source that unfolds over the dimension of time, Things like data from Firebase, DOM events, WebSockets, file uploads, etcetera. The first thing you'll need to do is install RxJS. I'm currently running version 6.4. Now I'm just using vanilla JavaScript with Webpack, but feel free to follow along with your favorite JavaScript framework.

The most fundamental class in RxJS is the observable. You can think of it as a wrapper for some data that can be subscribed to, and then the subscriber will be notified anytime the data changes. When working with RxJS, you should think of yourself as a plumber. And I mean that in the most literal sense because an observable is essentially a pipe for data and RxJS gives you all kinds of tools to modify those pipes. Let's go ahead and create our first observable, but first we need to import the RxJS library, and there's a right and a wrong way to do this.

Currently, I'm doing it the wrong way by using import star as RX, but that's going to cause the entire library to be bundled up in our code. You can see down here we have a bundle size of 47 kilobytes, but RxJS is a tree shakeable library, which means we only have to import the code that we actually need. So when working with RxJS, you should only import the classes and operators that you actually need in your source code. And by doing that, we reduce our bundle size to less than 2 kilobytes. Now that you know that, let's go ahead and create an observable from scratch.

Now you won't normally create observables like this in your own code, but it's a good exercise to understand what an observable is. When we call observable create, it gives us a callback function that we can use to notify a subscriber with some new data. This can be synchronous or asynchronous. But, basically, every time we call next, it's like emitting an event to the subscriber that they can listen to and react to. Now that we have our observable created, we can create to that observable by calling subscribe on it.

Subscribe takes a function that will be called every time the observable emits a new value. And this is why they call it reactive programming because with your subscription, And you're reacting to changes in the observable data. Throughout this video, I'm using my own helper method called print, which will react to each newly emitted item and print it to the DOM so we can visualize what's happening in the observable. And if we open this in the browser, you can see we get a b c logged 1 after the other. Another important concept to keep in mind is that observables can be completed, which means they'll be shut off and no longer emit values.

If we had observer complete and then go back to the browser, you can see that Only a and b are emitted, and that's because the stream has been closed. If you think like a plumber, creating the observable is like connecting a pipe to a water source And then subscribing is like opening the valve that lets that water out. RxJS provides a bunch of helper functions that make it easier to create observables. For example, if we want to just create an observable of a raw value, we can use of. This will just take the value that you pass in and wrap it in an observable.

If we subscribe to this, then we'll just get hello printed out in the console. Now the of function is very easy to mix up with the from function, which takes an array, promise, or iterable and then emits each individual item from the observable. We can see the difference by passing in a string, which itself That's iterable. Instead of emitting the entire string as one event, it emits each individual character in that string. Another thing we can do is create an observable from events in the DOM.

Using from event, we first pass in a DOM element and then the event that we wanna listen to. If we listen to clicks on the document and subscribe to the observable, we'll get an event every time we click on the page. Another thing we can do is set up an observable based on a time interval. It takes the number of milliseconds as its argument and then will emit a number each time that interval passes. Now Now one thing that a lot of people don't realize is that RxJS can be synchronous or asynchronous.

And you'll probably never have to do this, but you can control that behavior by modifying schedulers. If you get lost in this next example, I would recommend watching my async await video, which will teach you all about the event loop in JavaScript. Let's go ahead and define a string observable using of, and then we'll just synchronously call our print method with world. In this case, RxJS is going to treat that observable as a synchronous value. So the subscription will happen on the main thread.

Therefore, we get hello, world printed 1 after the other. You can change this behavior by modifying the scheduler of the observable. If we pass in the async Scheduler, it will emit the value of the observable on the next iteration of the event loop. This time in the browser, we get world hello. And, again, you'll probably never need to mess with that, but I just wanna give you an idea of Schedulers do.

The next thing we'll do is look at the difference between hot and cold observables. I don't really like this terminology, and I think the best way to think of it is observables can have multiple subscriptions whereas cold observables can only have one subscription. Cold observables don't actually create the underlying value until they're subscribed to. We'll go ahead and create an observable from scratch and just have it generate a random number. Now if we subscribe to this observable twice, you'll see that we get 2 different random numbers.

That's because that create callback function isn't called until the subscription is created. But often in the real world, that's not what you actually want. A lot Times RxJS is valuable because you can share a value across multiple subscribers. If you have an existing cold observable, there are multiple ways to make it hot or in other words, allow it to be broadcast to multiple subscribers. Now in this example, only the first subscriber will get the actual value.

But what's often useful in the real world is to use the share replay operator, which will cache the last value as well. If instead we pipe in share replay 1, you can see that both will get the same random number. Now in my experience, I'm not usually taking cold observables and making them hot. Instead, I'm creating subjects or behavior subjects. You can think of a subject as a hot observable, but it has the added benefit of being able to have new values pushed to it.

In plumbing terms, it's more like a pump where you can add new values to the stream after it's been created. We can do this easily by just instantiating a new subject, and then we can subscribe to it just like we've done with our other observables. What's unique about it is that it has a next method that we can call to add new values to the stream. Now a potential gotcha with a regular subject is that you need to have the subscription set up before you start adding values to it. You can see here in this first example, we subscribe, then we add 2 new values to it, then we set up a second subscriber.

And what you intuitively might think is that both subscribers will get the same values. But that's not true for the second subscriber, which will get nothing because it Subscribe late after the values were already added. And that brings me to one of the most useful things in RxJS, which is the behavior subject. It's similar to the subject we just looked at, except it has the concept of a current value. This means the last emitted value will be cached similar to how we set it up with share replay earlier.

But most importantly, it means that every subscription will always receive a value. Even though our second subscriber came in late, it still gets the last emitted value in the stream. That tends to be a very powerful feature when doing things like state management and front end applications. At this point, we've only been talking about creating observables. Now it's time to look at operators, which help you control the Flow of data going through your observables.

There are a ton of operators built into RxJS, so we'll just look at a handful of some of the most popular ones. First, we'll create a source observable that emits the integers 1 through 10. You can compose multiple operators together by using a pipe. And just like it sounds, your data will flow through this pipe and then be modified by each function or operator in the pipe. If we subscribe to the empty pipe, it just emits the values of 1 through 10.

To take the input and simply transform it to a new output, you can use the map operator. For example, we can take each number and then raise it to the power 2. Now the observable emits the square of the initial numbers. Another thing we can do is accumulate values as they flow through the observable similar to array reduce. If we wanna keep a running total of all the values that were emitted in this observable, we can use the scan operator and then add the current value to the accumulated value.

Now each emitted value gets added on top of the previous one. An important thing to keep in mind here is that the order of operation matters. For example, if we move the scan operator before the map operator, we're going to Different results because the underlying math is now different. So that's how you transform values. But another useful operator is filter which prevents certain items from being emitted in the stream.

For example, if we only want values that are greater than 10, we can use the filter operator and that will only emit values that meet this condition. And now we only see values that are greater than 10 printed in the UI. Another thing we can do with operators is tell the observable to complete. For example, if we pipe in take 3, it will only emit 3 values from this observable then complete it. The next thing I wanna show you is an operator called tap, which allows you to trigger side effects from inside the observable pipe.

In all the examples so Far, I've been printing values to the screen by using the callback in the subscribe method, but that only gives us access to the value at the end of the pipe. Most simple use case that you'll find is just console logging at different points within the observable pipe. The pipe modifies things from top to bottom. So if we add a tap to the very beginning, it's going to print the initial value. And if we map it to something else and add another tap after that, it's going to print a different value.

And you can use tap to trigger more complex side effects. For example, you might want to save a value from the observable to a back end database. If you're using something like Firebase, bass, you'll probably wanna use an async function. So basically, it just gives you a context to tap into the observable and do something. Another term you might hear with RxJS is backpressure.

And, basically, that means you have an observable that's emitting way more values than you actually need. We can simulate this in the code by listening to the mouse move event on the DOM. Moving the mouse across the screen will cause the observable to emit multiple events every second. RXJS has several operators that can help us with this situation. The first strategy we'll look at is to debounce the events.

A debounce will filter out all events until they have stopped happening for a certain period of time, in this case, a 1000 milliseconds. A debounce is really useful for something like a type ahead where you don't wanna make an API call until the user is done typing. You can see here if we mouse around for a little while, nothing happens. Then if we stop, Our event will be emitted after one second. An alternative to a debounce is a throttle.

It will emit the first value, but make sure that no additional values can be emitted until a certain time period has passed. We go back to the demo and start moving around, at the very most, we'll get one event emitted per second. These operators are alleviating the back pressure, but they're also filtering out a lot of data. If we want to keep all the data but just not listen to it all at once, we can use a buffer. This will collect all the events into an array and then only emit them when they get to a length of 20.

Now we're going to switch gears to another very important operator called switch map. This allows you to start with one observable and then switch to another one, which is very important when we're talking about data. For example, if you're a Firebase user, you probably have an observable of a user logged into your app, and then you might want to switch to another observable of Some information about that user in the database. We can simulate that in our code by creating an observable of an object, and then I'll create a function that returns an observable of Some information based on a user ID. We can't call this function until we have a user ID.

So the question becomes, how do we get the user ID out of the observable? The naive way to do this is to nest subscriptions within each other. So first, we subscribe to the user. That'll give us the user ID. Then we create another description inside of that callback for the orders.

That code will actually work, but there's a better way to do this. Instead, we'll start with our user observable To compose a new observable called orders, we first add a pipe to the user and then we use the switch map operator, which will give us access to the user ID. And then we just return an observable from it, and you can also return a promise or an array here as well. So if you ever have one value that depends on another value, switch map might be the operator that you're looking for. But there might be other cases where you have multiple observables that you just want to combine into a single stream.

We'll look at 2 different functions here called combine latest and merge. And keep in mind these are not technically operators, so we import them directly from RxJS. I'm creating a cold observable of a random number then I'm creating a second observable that just adds a delay to that random number. 1st, we'll use combine latest and it takes an array of observables And it will wait for each observable to emit a value and then emit everything together as an array. Even though the random numbers are going to emit something right away, going to wait for that delay to resolve into a value before it emits anything.

Then if any of the observables emit anything after that, it will emit everything again as an array. In other words, it gives you the current state of every observable in this array. So initially, it's blank for one second waiting for that delay and then it emits out the 4 random numbers. In many cases, though, you don't want to wait for that delay. So instead, you can use merge which will just emit each value 1 by 1 as it comes in through the stream.

Merge doesn't care about the array position of the observable. It only cares about when it emits it in the context of time. So it emits the first three values and then the delayed value a second later. Another thing you might be wondering is how to catch errors in the context of a stream. You have a lot of flexibility here, but one of the most common strategies is to catch the error and then replace it with some other value.

We can do this easily with the catch error operator. It can intercept the error and then emit some other default value out of the stream. And one thing that's really nice about RxJS is you can easily retry Try things by just piping in the retry operator. I'm not going to get into it here, but it's super useful when working with HTTP calls. 1st, I'll push a regular value and then an error to the subject.

If we don't catch the error, we'll get this uncaught error in the console. But by using the catch error operator, we can handle it in the background and then provide some useful information to the user in the front end. Now if you're a good plumber, then you shouldn't have pipes that leak. And by that, I'm talking about memory leaks. There are 2 main ways to prevent memory leaks with RxJS.

The first way is to unsubscribe from your subscriptions. Take, for example, this interval. This interval is going to run forever. So if we don't close the subscription, it's just going to create a memory leak in the background. One potential way to handle this is to create a variable for the subscription and then call subscription unsubscribe at some other point in the code.

This will stop the leak because we can see here the observable only emits 10 values, but there's actually a better way we can do this. We can pipe in the take while operator to the interval itself And that will tell it to emit values only while a certain condition is true. When that condition becomes false, it will stop emitting values, therefore, preventing the memory leak. And we don't need to manually unsubscribe anywhere in our code. That works well in a lot of situations, but sometimes you want some other observable or subject to be the thing that triggers the subscription to stop.

For that, we have the take and tell operator and it takes an observable as its argument. And when that observable emits something, it will cancel the subscription on the source. For example, if we wanted to set a timer for 2 2nd on this interval, we could do that by using take and tell with a timer observable. When the timer finishes it will complete the interval and then end the subscription. Gonna go ahead and wrap things up there.

We barely just scratched the surface with RXJS, so let me know what you wanna see next in the comments. If this video helped you, please like and subscribe. Thanks for watching and I will talk to you soon.
One of the most difficult but also most rewarding JavaScript libraries to learn is RxJS. It's a tool that helps us control data as it flows through the dimension of Time. In today's episode of Code This Not That, you'll learn 10 fundamental concepts in RxJS and how to avoid the bad stuff.
machine learning
If you're new here, like and Subscribe and leave me a comment below for a chance to win this t shirt next week. Arc's JS is getting pretty popular these days. In fact, it gets more daily NPM PM downloads, then Angular, React, and Vue. And the only functional library that I'm aware of that's bigger is Lodash. And the reason it's so popular is because JavaScript alone doesn't give us quite everything We would like to work with asynchronous streams of data.
We have promises, but they only work with a single async value. So we use callbacks for real time streams, but you've probably heard the term callback help. RxJS addresses these issues and gives us a powerful functional library for dealing with streams. And when I say stream, I'm talking about any data source that unfolds over the dimension of time, Things like data from Firebase, DOM events, WebSockets, file uploads, etcetera. The first thing you'll need to do is install RxJS.
streaming
I'm currently running version 6.4. Now I'm just using vanilla JavaScript with Webpack, but feel free to follow along with your favorite JavaScript framework. The most fundamental class in RxJS is the observable. You can think of it as a wrapper for some data that can be subscribed to, and then the subscriber will be notified anytime the data changes. When working with RxJS, you should think of yourself as a plumber. And I mean that in the most literal sense because an observable is essentially a pipe for data and RxJS gives you all kinds of tools to modify those pipes. Let's go ahead and create our first observable, but first we need to import the RxJS library, and there's a right and a wrong way to do this. Currently, I'm doing it the wrong way by using import star as RX, but that's going to cause the entire library to be bundled up in our code. You can see down here we have a bundle size of 47 kilobytes, but RxJS is a tree shakeable library, which means we only have to import the code that we actually need. So when working with RxJS, you should only import the classes and operators that you actually need in your source code. And by doing that, we reduce our bundle size to less than 2 kilobytes. Now that you know that, let's go ahead and create an observable from scratch. Now you won't normally create observables like this in your own code, but it's a good exercise to understand what an observable is. When we call observable create, it gives us a callback function that we can use to notify a subscriber with some new data. This can be synchronous or asynchronous. But, basically, every time we call next, it's like emitting an event to the subscriber that they can listen to and react to. Now that we have our observable created, we can create to that observable by calling subscribe on it. Subscribe takes a function that will be called every time the observable emits a new value. And this is why they call it reactive programming because with your subscription, And you're reacting to changes in the observable data.
Throughout this video, I'm using my own helper method called print, which will react to each newly emitted item and print it to the DOM so we can visualize what's happening in the observable. And if we open this in the browser, you can see we get a b c logged 1 after the other.
visualization
programming
Another important concept to keep in mind is that observables can be completed, which means they'll be shut off and no longer emit values. If we had observer complete and then go back to the browser, you can see that Only a and b are emitted, and that's because the stream has been closed. If you think like a plumber, creating the observable is like connecting a pipe to a water source And then subscribing is like opening the valve that lets that water out.
RxJS provides a bunch of helper functions that make it easier to create observables. For example, if we want to just create an observable of a raw value, we can use of. This will just take the value that you pass in and wrap it in an observable. If we subscribe to this, then we'll just get hello printed out in the console. Now the of function is very easy to mix up with the from function, which takes an array, promise, or iterable and then emits each individual item from the observable.
programming
We can see the difference by passing in a string, which itself That's iterable. Instead of emitting the entire string as one event, it emits each individual character in that string. Another thing we can do is create an observable from events in the DOM. Using from event, we first pass in a DOM element and then the event that we wanna listen to. If we listen to clicks on the document and subscribe to the observable, we'll get an event every time we click on the page. Another thing we can do is set up an observable based on a time interval. It takes the number of milliseconds as its argument and then will emit a number each time that interval passes. Now Now one thing that a lot of people don't realize is that RxJS can be synchronous or asynchronous.
And you'll probably never have to do this, but you can control that behavior by modifying schedulers. If you get lost in this next example, I would recommend watching my async await video, which will teach you all about the event loop in JavaScript. Let's go ahead and define a string observable using of, and then we'll just synchronously call our print method with world. In this case, RxJS is going to treat that observable as a synchronous value. So the subscription will happen on the main thread. Therefore, we get hello, world printed 1 after the other.
programming
You can change this behavior by modifying the scheduler of the observable. If we pass in the async Scheduler, it will emit the value of the observable on the next iteration of the event loop. This time in the browser, we get world hello. And, again, you'll probably never need to mess with that, but I just wanna give you an idea of Schedulers do. The next thing we'll do is look at the difference between hot and cold observables. I don't really like this terminology, and I think the best way to think of it is observables can have multiple subscriptions whereas cold observables can only have one subscription.
Cold observables don't actually create the underlying value until they're subscribed to. We'll go ahead and create an observable from scratch and just have it generate a random number. Now if we subscribe to this observable twice, you'll see that we get 2 different random numbers. That's because that create callback function isn't called until the subscription is created.
probability
But often in the real world, that's not what you actually want. A lot Times RxJS is valuable because you can share a value across multiple subscribers.
If you have an existing cold observable, there are multiple ways to make it hot or in other words, allow it to be broadcast to multiple subscribers. Now in this example, only the first subscriber will get the actual value. But what's often useful in the real world is to use the share replay operator, which will cache the last value as well. If instead we pipe in share replay 1, you can see that both will get the same random number.
streaming
probability
Now in my experience, I'm not usually taking cold observables and making them hot. Instead, I'm creating subjects or behavior subjects. You can think of a subject as a hot observable, but it has the added benefit of being able to have new values pushed to it. In plumbing terms, it's more like a pump where you can add new values to the stream after it's been created. We can do this easily by just instantiating a new subject, and then we can subscribe to it just like we've done with our other observables. What's unique about it is that it has a next method that we can call to add new values to the stream. Now a potential gotcha with a regular subject is that you need to have the subscription set up before you start adding values to it. You can see here in this first example, we subscribe, then we add 2 new values to it, then we set up a second subscriber. And what you intuitively might think is that both subscribers will get the same values. But that's not true for the second subscriber, which will get nothing because it Subscribe late after the values were already added. And that brings me to one of the most useful things in RxJS, which is the behavior subject. It's similar to the subject we just looked at, except it has the concept of a current value. This means the last emitted value will be cached similar to how we set it up with share replay earlier. But most importantly, it means that every subscription will always receive a value.
Even though our second subscriber came in late, it still gets the last emitted value in the stream. That tends to be a very powerful feature when doing things like state management and front end applications. At this point, we've only been talking about creating observables. Now it's time to look at operators, which help you control the Flow of data going through your observables.
data management
systems
There are a ton of operators built into RxJS, so we'll just look at a handful of some of the most popular ones. First, we'll create a source observable that emits the integers 1 through 10. You can compose multiple operators together by using a pipe. And just like it sounds, your data will flow through this pipe and then be modified by each function or operator in the pipe.
programming
If we subscribe to the empty pipe, it just emits the values of 1 through 10. To take the input and simply transform it to a new output, you can use the map operator.
For example, we can take each number and then raise it to the power 2. Now the observable emits the square of the initial numbers. Another thing we can do is accumulate values as they flow through the observable similar to array reduce. If we wanna keep a running total of all the values that were emitted in this observable, we can use the scan operator and then add the current value to the accumulated value. Now each emitted value gets added on top of the previous one. An important thing to keep in mind here is that the order of operation matters. For example, if we move the scan operator before the map operator, we're going to Different results because the underlying math is now different.
operations
data
So that's how you transform values. But another useful operator is filter which prevents certain items from being emitted in the stream. For example, if we only want values that are greater than 10, we can use the filter operator and that will only emit values that meet this condition.
And now we only see values that are greater than 10 printed in the UI. Another thing we can do with operators is tell the observable to complete. For example, if we pipe in take 3, it will only emit 3 values from this observable then complete it. The next thing I wanna show you is an operator called tap, which allows you to trigger side effects from inside the observable pipe.
operations
programming
In all the examples so Far, I've been printing values to the screen by using the callback in the subscribe method, but that only gives us access to the value at the end of the pipe. Most simple use case that you'll find is just console logging at different points within the observable pipe. The pipe modifies things from top to bottom. So if we add a tap to the very beginning, it's going to print the initial value. And if we map it to something else and add another tap after that, it's going to print a different value. And you can use tap to trigger more complex side effects. For example, you might want to save a value from the observable to a back end database.
programming
If you're using something like Firebase, bass, you'll probably wanna use an async function. So basically, it just gives you a context to tap into the observable and do something. Another term you might hear with RxJS is backpressure. And, basically, that means you have an observable that's emitting way more values than you actually need.
We can simulate this in the code by listening to the mouse move event on the DOM. Moving the mouse across the screen will cause the observable to emit multiple events every second. RXJS has several operators that can help us with this situation. The first strategy we'll look at is to debounce the events.
animation
A debounce will filter out all events until they have stopped happening for a certain period of time, in this case, a 1000 milliseconds. A debounce is really useful for something like a type ahead where you don't wanna make an API call until the user is done typing. You can see here if we mouse around for a little while, nothing happens. Then if we stop, Our event will be emitted after one second. An alternative to a debounce is a throttle. It will emit the first value, but make sure that no additional values can be emitted until a certain time period has passed. We go back to the demo and start moving around, at the very most, we'll get one event emitted per second. These operators are alleviating the back pressure, but they're also filtering out a lot of data. If we want to keep all the data but just not listen to it all at once, we can use a buffer. This will collect all the events into an array and then only emit them when they get to a length of 20. Now we're going to switch gears to another very important operator called switch map. This allows you to start with one observable and then switch to another one, which is very important when we're talking about data. For example, if you're a Firebase user, you probably have an observable of a user logged into your app, and then you might want to switch to another observable of Some information about that user in the database.
We can simulate that in our code by creating an observable of an object, and then I'll create a function that returns an observable of Some information based on a user ID. We can't call this function until we have a user ID. So the question becomes, how do we get the user ID out of the observable?
programming
The naive way to do this is to nest subscriptions within each other. So first, we subscribe to the user. That'll give us the user ID.
Then we create another description inside of that callback for the orders. That code will actually work, but there's a better way to do this. Instead, we'll start with our user observable To compose a new observable called orders, we first add a pipe to the user and then we use the switch map operator, which will give us access to the user ID. And then we just return an observable from it, and you can also return a promise or an array here as well.
programming
So if you ever have one value that depends on another value, switch map might be the operator that you're looking for. But there might be other cases where you have multiple observables that you just want to combine into a single stream. We'll look at 2 different functions here called combine latest and merge.
And keep in mind these are not technically operators, so we import them directly from RxJS. I'm creating a cold observable of a random number then I'm creating a second observable that just adds a delay to that random number. 1st, we'll use combine latest and it takes an array of observables And it will wait for each observable to emit a value and then emit everything together as an array.
programming
Even though the random numbers are going to emit something right away, going to wait for that delay to resolve into a value before it emits anything. Then if any of the observables emit anything after that, it will emit everything again as an array. In other words, it gives you the current state of every observable in this array. So initially, it's blank for one second waiting for that delay and then it emits out the 4 random numbers. In many cases, though, you don't want to wait for that delay. So instead, you can use merge which will just emit each value 1 by 1 as it comes in through the stream. Merge doesn't care about the array position of the observable. It only cares about when it emits it in the context of time. So it emits the first three values and then the delayed value a second later.
Another thing you might be wondering is how to catch errors in the context of a stream. You have a lot of flexibility here, but one of the most common strategies is to catch the error and then replace it with some other value. We can do this easily with the catch error operator.
fishing
It can intercept the error and then emit some other default value out of the stream. And one thing that's really nice about RxJS is you can easily retry Try things by just piping in the retry operator. I'm not going to get into it here, but it's super useful when working with HTTP calls. 1st, I'll push a regular value and then an error to the subject. If we don't catch the error, we'll get this uncaught error in the console. But by using the catch error operator, we can handle it in the background and then provide some useful information to the user in the front end. Now if you're a good plumber, then you shouldn't have pipes that leak. And by that, I'm talking about memory leaks. There are 2 main ways to prevent memory leaks with RxJS. The first way is to unsubscribe from your subscriptions. Take, for example, this interval. This interval is going to run forever. So if we don't close the subscription, it's just going to create a memory leak in the background. One potential way to handle this is to create a variable for the subscription and then call subscription unsubscribe at some other point in the code. This will stop the leak because we can see here the observable only emits 10 values, but there's actually a better way we can do this. We can pipe in the take while operator to the interval itself And that will tell it to emit values only while a certain condition is true. When that condition becomes false, it will stop emitting values, therefore, preventing the memory leak. And we don't need to manually unsubscribe anywhere in our code. That works well in a lot of situations, but sometimes you want some other observable or subject to be the thing that triggers the subscription to stop. For that, we have the take and tell operator and it takes an observable as its argument. And when that observable emits something, it will cancel the subscription on the source. For example, if we wanted to set a timer for 2 2nd on this interval, we could do that by using take and tell with a timer observable.
When the timer finishes it will complete the interval and then end the subscription. Gonna go ahead and wrap things up there. We barely just scratched the surface with RXJS, so let me know what you wanna see next in the comments. If this video helped you, please like and subscribe. Thanks for watching and I will talk to you soon.
youtube
multimedia
documentary
One of the most difficult but also most rewarding JavaScript libraries to learn is RxJS. It's a tool that helps us control data as it flows through the dimension of Time. In today's episode of Code This Not That, you'll learn 10 fundamental concepts in RxJS and how to avoid the bad stuff. If you're new here, like and Subscribe and leave me a comment below for a chance to win this t shirt next week. Arc's JS is getting pretty popular these days. In fact, it gets more daily NPM PM downloads, then Angular, React, and Vue. And the only functional library that I'm aware of that's bigger is Lodash. And the reason it's so popular is because JavaScript alone doesn't give us quite everything We would like to work with asynchronous streams of data. We have promises, but they only work with a single async value. So we use callbacks for real time streams, but you've probably heard the term callback help. RxJS addresses these issues and gives us a powerful functional library for dealing with streams. And when I say stream, I'm talking about any data source that unfolds over the dimension of time, Things like data from Firebase, DOM events, WebSockets, file uploads, etcetera. The first thing you'll need to do is install RxJS. I'm currently running version 6.4. Now I'm just using vanilla JavaScript with Webpack, but feel free to follow along with your favorite JavaScript framework. The most fundamental class in RxJS is the observable. You can think of it as a wrapper for some data that can be subscribed to, and then the subscriber will be notified anytime the data changes. When working with RxJS, you should think of yourself as a plumber. And I mean that in the most literal sense because an observable is essentially a pipe for data and RxJS gives you all kinds of tools to modify those pipes. Let's go ahead and create our first observable, but first we need to import the RxJS library, and there's a right and a wrong way to do this. Currently, I'm doing it the wrong way by using import star as RX, but that's going to cause the entire library to be bundled up in our code. You can see down here we have a bundle size of 47 kilobytes, but RxJS is a tree shakeable library, which means we only have to import the code that we actually need. So when working with RxJS, you should only import the classes and operators that you actually need in your source code. And by doing that, we reduce our bundle size to less than 2 kilobytes. Now that you know that, let's go ahead and create an observable from scratch. Now you won't normally create observables like this in your own code, but it's a good exercise to understand what an observable is. When we call observable create, it gives us a callback function that we can use to notify a subscriber with some new data. This can be synchronous or asynchronous. But, basically, every time we call next, it's like emitting an event to the subscriber that they can listen to and react to. Now that we have our observable created, we can create to that observable by calling subscribe on it. Subscribe takes a function that will be called every time the observable emits a new value. And this is why they call it reactive programming because with your subscription, And you're reacting to changes in the observable data. Throughout this video, I'm using my own helper method called print, which will react to each newly emitted item and print it to the DOM so we can visualize what's happening in the observable. And if we open this in the browser, you can see we get a b c logged 1 after the other. Another important concept to keep in mind is that observables can be completed, which means they'll be shut off and no longer emit values. If we had observer complete and then go back to the browser, you can see that Only a and b are emitted, and that's because the stream has been closed. If you think like a plumber, creating the observable is like connecting a pipe to a water source And then subscribing is like opening the valve that lets that water out. RxJS provides a bunch of helper functions that make it easier to create observables. For example, if we want to just create an observable of a raw value, we can use of. This will just take the value that you pass in and wrap it in an observable. If we subscribe to this, then we'll just get hello printed out in the console. Now the of function is very easy to mix up with the from function, which takes an array, promise, or iterable and then emits each individual item from the observable. We can see the difference by passing in a string, which itself That's iterable. Instead of emitting the entire string as one event, it emits each individual character in that string. Another thing we can do is create an observable from events in the DOM. Using from event, we first pass in a DOM element and then the event that we wanna listen to. If we listen to clicks on the document and subscribe to the observable, we'll get an event every time we click on the page. Another thing we can do is set up an observable based on a time interval. It takes the number of milliseconds as its argument and then will emit a number each time that interval passes. Now Now one thing that a lot of people don't realize is that RxJS can be synchronous or asynchronous. And you'll probably never have to do this, but you can control that behavior by modifying schedulers. If you get lost in this next example, I would recommend watching my async await video, which will teach you all about the event loop in JavaScript. Let's go ahead and define a string observable using of, and then we'll just synchronously call our print method with world. In this case, RxJS is going to treat that observable as a synchronous value. So the subscription will happen on the main thread. Therefore, we get hello, world printed 1 after the other. You can change this behavior by modifying the scheduler of the observable. If we pass in the async Scheduler, it will emit the value of the observable on the next iteration of the event loop. This time in the browser, we get world hello. And, again, you'll probably never need to mess with that, but I just wanna give you an idea of Schedulers do. The next thing we'll do is look at the difference between hot and cold observables. I don't really like this terminology, and I think the best way to think of it is observables can have multiple subscriptions whereas cold observables can only have one subscription. Cold observables don't actually create the underlying value until they're subscribed to. We'll go ahead and create an observable from scratch and just have it generate a random number. Now if we subscribe to this observable twice, you'll see that we get 2 different random numbers. That's because that create callback function isn't called until the subscription is created. But often in the real world, that's not what you actually want. A lot Times RxJS is valuable because you can share a value across multiple subscribers. If you have an existing cold observable, there are multiple ways to make it hot or in other words, allow it to be broadcast to multiple subscribers. Now in this example, only the first subscriber will get the actual value. But what's often useful in the real world is to use the share replay operator, which will cache the last value as well. If instead we pipe in share replay 1, you can see that both will get the same random number. Now in my experience, I'm not usually taking cold observables and making them hot. Instead, I'm creating subjects or behavior subjects. You can think of a subject as a hot observable, but it has the added benefit of being able to have new values pushed to it. In plumbing terms, it's more like a pump where you can add new values to the stream after it's been created. We can do this easily by just instantiating a new subject, and then we can subscribe to it just like we've done with our other observables. What's unique about it is that it has a next method that we can call to add new values to the stream. Now a potential gotcha with a regular subject is that you need to have the subscription set up before you start adding values to it. You can see here in this first example, we subscribe, then we add 2 new values to it, then we set up a second subscriber. And what you intuitively might think is that both subscribers will get the same values. But that's not true for the second subscriber, which will get nothing because it Subscribe late after the values were already added. And that brings me to one of the most useful things in RxJS, which is the behavior subject. It's similar to the subject we just looked at, except it has the concept of a current value. This means the last emitted value will be cached similar to how we set it up with share replay earlier. But most importantly, it means that every subscription will always receive a value. Even though our second subscriber came in late, it still gets the last emitted value in the stream. That tends to be a very powerful feature when doing things like state management and front end applications. At this point, we've only been talking about creating observables. Now it's time to look at operators, which help you control the Flow of data going through your observables. There are a ton of operators built into RxJS, so we'll just look at a handful of some of the most popular ones. First, we'll create a source observable that emits the integers 1 through 10. You can compose multiple operators together by using a pipe. And just like it sounds, your data will flow through this pipe and then be modified by each function or operator in the pipe. If we subscribe to the empty pipe, it just emits the values of 1 through 10. To take the input and simply transform it to a new output, you can use the map operator. For example, we can take each number and then raise it to the power 2. Now the observable emits the square of the initial numbers. Another thing we can do is accumulate values as they flow through the observable similar to array reduce. If we wanna keep a running total of all the values that were emitted in this observable, we can use the scan operator and then add the current value to the accumulated value. Now each emitted value gets added on top of the previous one. An important thing to keep in mind here is that the order of operation matters. For example, if we move the scan operator before the map operator, we're going to Different results because the underlying math is now different. So that's how you transform values. But another useful operator is filter which prevents certain items from being emitted in the stream. For example, if we only want values that are greater than 10, we can use the filter operator and that will only emit values that meet this condition. And now we only see values that are greater than 10 printed in the UI. Another thing we can do with operators is tell the observable to complete. For example, if we pipe in take 3, it will only emit 3 values from this observable then complete it. The next thing I wanna show you is an operator called tap, which allows you to trigger side effects from inside the observable pipe. In all the examples so Far, I've been printing values to the screen by using the callback in the subscribe method, but that only gives us access to the value at the end of the pipe. Most simple use case that you'll find is just console logging at different points within the observable pipe. The pipe modifies things from top to bottom. So if we add a tap to the very beginning, it's going to print the initial value. And if we map it to something else and add another tap after that, it's going to print a different value. And you can use tap to trigger more complex side effects. For example, you might want to save a value from the observable to a back end database. If you're using something like Firebase, bass, you'll probably wanna use an async function. So basically, it just gives you a context to tap into the observable and do something. Another term you might hear with RxJS is backpressure. And, basically, that means you have an observable that's emitting way more values than you actually need. We can simulate this in the code by listening to the mouse move event on the DOM. Moving the mouse across the screen will cause the observable to emit multiple events every second. RXJS has several operators that can help us with this situation. The first strategy we'll look at is to debounce the events. A debounce will filter out all events until they have stopped happening for a certain period of time, in this case, a 1000 milliseconds. A debounce is really useful for something like a type ahead where you don't wanna make an API call until the user is done typing. You can see here if we mouse around for a little while, nothing happens. Then if we stop, Our event will be emitted after one second. An alternative to a debounce is a throttle. It will emit the first value, but make sure that no additional values can be emitted until a certain time period has passed. We go back to the demo and start moving around, at the very most, we'll get one event emitted per second. These operators are alleviating the back pressure, but they're also filtering out a lot of data. If we want to keep all the data but just not listen to it all at once, we can use a buffer. This will collect all the events into an array and then only emit them when they get to a length of 20. Now we're going to switch gears to another very important operator called switch map. This allows you to start with one observable and then switch to another one, which is very important when we're talking about data. For example, if you're a Firebase user, you probably have an observable of a user logged into your app, and then you might want to switch to another observable of Some information about that user in the database. We can simulate that in our code by creating an observable of an object, and then I'll create a function that returns an observable of Some information based on a user ID. We can't call this function until we have a user ID. So the question becomes, how do we get the user ID out of the observable? The naive way to do this is to nest subscriptions within each other. So first, we subscribe to the user. That'll give us the user ID. Then we create another description inside of that callback for the orders. That code will actually work, but there's a better way to do this. Instead, we'll start with our user observable To compose a new observable called orders, we first add a pipe to the user and then we use the switch map operator, which will give us access to the user ID. And then we just return an observable from it, and you can also return a promise or an array here as well. So if you ever have one value that depends on another value, switch map might be the operator that you're looking for. But there might be other cases where you have multiple observables that you just want to combine into a single stream. We'll look at 2 different functions here called combine latest and merge. And keep in mind these are not technically operators, so we import them directly from RxJS. I'm creating a cold observable of a random number then I'm creating a second observable that just adds a delay to that random number. 1st, we'll use combine latest and it takes an array of observables And it will wait for each observable to emit a value and then emit everything together as an array. Even though the random numbers are going to emit something right away, going to wait for that delay to resolve into a value before it emits anything. Then if any of the observables emit anything after that, it will emit everything again as an array. In other words, it gives you the current state of every observable in this array. So initially, it's blank for one second waiting for that delay and then it emits out the 4 random numbers. In many cases, though, you don't want to wait for that delay. So instead, you can use merge which will just emit each value 1 by 1 as it comes in through the stream. Merge doesn't care about the array position of the observable. It only cares about when it emits it in the context of time. So it emits the first three values and then the delayed value a second later. Another thing you might be wondering is how to catch errors in the context of a stream. You have a lot of flexibility here, but one of the most common strategies is to catch the error and then replace it with some other value. We can do this easily with the catch error operator. It can intercept the error and then emit some other default value out of the stream. And one thing that's really nice about RxJS is you can easily retry Try things by just piping in the retry operator. I'm not going to get into it here, but it's super useful when working with HTTP calls. 1st, I'll push a regular value and then an error to the subject. If we don't catch the error, we'll get this uncaught error in the console. But by using the catch error operator, we can handle it in the background and then provide some useful information to the user in the front end. Now if you're a good plumber, then you shouldn't have pipes that leak. And by that, I'm talking about memory leaks. There are 2 main ways to prevent memory leaks with RxJS. The first way is to unsubscribe from your subscriptions. Take, for example, this interval. This interval is going to run forever. So if we don't close the subscription, it's just going to create a memory leak in the background. One potential way to handle this is to create a variable for the subscription and then call subscription unsubscribe at some other point in the code. This will stop the leak because we can see here the observable only emits 10 values, but there's actually a better way we can do this. We can pipe in the take while operator to the interval itself And that will tell it to emit values only while a certain condition is true. When that condition becomes false, it will stop emitting values, therefore, preventing the memory leak. And we don't need to manually unsubscribe anywhere in our code. That works well in a lot of situations, but sometimes you want some other observable or subject to be the thing that triggers the subscription to stop. For that, we have the take and tell operator and it takes an observable as its argument. And when that observable emits something, it will cancel the subscription on the source. For example, if we wanted to set a timer for 2 2nd on this interval, we could do that by using take and tell with a timer observable. When the timer finishes it will complete the interval and then end the subscription. Gonna go ahead and wrap things up there. We barely just scratched the surface with RXJS, so let me know what you wanna see next in the comments. If this video helped you, please like and subscribe. Thanks for watching and I will talk to you soon.
One
one
of
of
the
the
most
most
difficult
difficult
but
but
also
also
most
most
rewarding
rewarding
JavaScript
javascript
libraries
libraries
to
to
learn
learn
is
is
RxJS.
rxjs
It's
it's
a
a
tool
tool
that
that
helps
helps
us
us
control
control
data
data
as
as
it
it
flows
flows
through
through
the
the
dimension
dimension
of
of
Time.
time
In
in
today's
today's
episode
episode
of
of
Code
code
This
this
Not
not
That,
that
you'll
you'll
learn
learn
10
10
fundamental
fundamental
concepts
concepts
in
in
RxJS
rxjs
and
and
how
how
to
to
avoid
avoid
the
the
bad
bad
stuff.
stuff
If
if
you're
you're
new
new
here,
here
like
like
and
and
Subscribe
subscribe
and
and
leave
leave
me
me
a
a
comment
comment
below
below
for
for
a
a
chance
chance
to
to
win
win
this
this
t
t
shirt
shirt
next
next
week.
week
Arc's
arc's
JS
js
is
is
getting
getting
pretty
pretty
popular
popular
these
these
days.
days
In
in
fact,
fact
it
it
gets
gets
more
more
daily
daily
NPM
npm
PM
pm
downloads,
downloads
then
then
Angular,
angular
React,
react
and
and
Vue.
vue
And
and
the
the
only
only
functional
functional
library
library
that
that
I'm
i'm
aware
aware
of
of
that's
that's
bigger
bigger
is
is
Lodash.
lodash
And
and
the
the
reason
reason
it's
it's
so
so
popular
popular
is
is
because
because
JavaScript
javascript
alone
alone
doesn't
doesn't
give
give
us
us
quite
quite
everything
everything
We
we
would
would
like
like
to
to
work
work
with
with
asynchronous
asynchronous
streams
streams
of
of
data.
data
We
we
have
have
promises,
promises
but
but
they
they
only
only
work
work
with
with
a
a
single
single
async
async
value.
value
So
so
we
we
use
use
callbacks
callbacks
for
for
real
real
time
time
streams,
streams
but
but
you've
you've
probably
probably
heard
heard
the
the
term
term
callback
callback
help.
help
RxJS
rxjs
addresses
addresses
these
these
issues
issues
and
and
gives
gives
us
us
a
a
powerful
powerful
functional
functional
library
library
for
for
dealing
dealing
with
with
streams.
streams
And
and
when
when
I
i
say
say
stream,
stream
I'm
i'm
talking
talking
about
about
any
any
data
data
source
source
that
that
unfolds
unfolds
over
over
the
the
dimension
dimension
of
of
time,
time
Things
things
like
like
data
data
from
from
Firebase,
firebase
DOM
dom
events,
events
WebSockets,
websockets
file
file
uploads,
uploads
etcetera.
etcetera
The
the
first
first
thing
thing
you'll
you'll
need
need
to
to
do
do
is
is
install
install
RxJS.
rxjs
I'm
i'm
currently
currently
running
running
version
version
6.4.
6.4
Now
now
I'm
i'm
just
just
using
using
vanilla
vanilla
JavaScript
javascript
with
with
Webpack,
webpack
but
but
feel
feel
free
free
to
to
follow
follow
along
along
with
with
your
your
favorite
favorite
JavaScript
javascript
framework.
framework
The
the
most
most
fundamental
fundamental
class
class
in
in
RxJS
rxjs
is
is
the
the
observable.
observable
You
you
can
can
think
think
of
of
it
it
as
as
a
a
wrapper
wrapper
for
for
some
some
data
data
that
that
can
can
be
be
subscribed
subscribed
to,
to
and
and
then
then
the
the
subscriber
subscriber
will
will
be
be
notified
notified
anytime
anytime
the
the
data
data
changes.
changes
When
when
working
working
with
with
RxJS,
rxjs
you
you
should
should
think
think
of
of
yourself
yourself
as
as
a
a
plumber.
plumber
And
and
I
i
mean
mean
that
that
in
in
the
the
most
most
literal
literal
sense
sense
because
because
an
an
observable
observable
is
is
essentially
essentially
a
a
pipe
pipe
for
for
data
data
and
and
RxJS
rxjs
gives
gives
you
you
all
all
kinds
kinds
of
of
tools
tools
to
to
modify
modify
those
those
pipes.
pipes
Let's
let's
go
go
ahead
ahead
and
and
create
create
our
our
first
first
observable,
observable
but
but
first
first
we
we
need
need
to
to
import
import
the
the
RxJS
rxjs
library,
library
and
and
there's
there's
a
a
right
right
and
and
a
a
wrong
wrong
way
way
to
to
do
do
this.
this
Currently,
currently
I'm
i'm
doing
doing
it
it
the
the
wrong
wrong
way
way
by
by
using
using
import
import
star
star
as
as
RX,
rx
but
but
that's
that's
going
going
to
to
cause
cause
the
the
entire
entire
library
library
to
to
be
be
bundled
bundled
up
up
in
in
our
our
code.
code
You
you
can
can
see
see
down
down
here
here
we
we
have
have
a
a
bundle
bundle
size
size
of
of
47
47
kilobytes,
kilobytes
but
but
RxJS
rxjs
is
is
a
a
tree
tree
shakeable
shakeable
library,
library
which
which
means
means
we
we
only
only
have
have
to
to
import
import
the
the
code
code
that
that
we
we
actually
actually
need.
need
So
so
when
when
working
working
with
with
RxJS,
rxjs
you
you
should
should
only
only
import
import
the
the
classes
classes
and
and
operators
operators
that
that
you
you
actually
actually
need
need
in
in
your
your
source
source
code.
code
And
and
by
by
doing
doing
that,
that
we
we
reduce
reduce
our
our
bundle
bundle
size
size
to
to
less
less
than
than
2
2
kilobytes.
kilobytes
Now
now
that
that
you
you
know
know
that,
that
let's
let's
go
go
ahead
ahead
and
and
create
create
an
an
observable
observable
from
from
scratch.
scratch
Now
now
you
you
won't
won't
normally
normally
create
create
observables
observables
like
like
this
this
in
in
your
your
own
own
code,
code
but
but
it's
it's
a
a
good
good
exercise
exercise
to
to
understand
understand
what
what
an
an
observable
observable
is.
is
When
when
we
we
call
call
observable
observable
create,
create
it
it
gives
gives
us
us
a
a
callback
callback
function
function
that
that
we
we
can
can
use
use
to
to
notify
notify
a
a
subscriber
subscriber
with
with
some
some
new
new
data.
data
This
this
can
can
be
be
synchronous
synchronous
or
or
asynchronous.
asynchronous
But,
but
basically,
basically
every
every
time
time
we
we
call
call
next,
next
it's
it's
like
like
emitting
emitting
an
an
event
event
to
to
the
the
subscriber
subscriber
that
that
they
they
can
can
listen
listen
to
to
and
and
react
react
to.
to
Now
now
that
that
we
we
have
have
our
our
observable
observable
created,
created
we
we
can
can
create
create
to
to
that
that
observable
observable
by
by
calling
calling
subscribe
subscribe
on
on
it.
it
Subscribe
subscribe
takes
takes
a
a
function
function
that
that
will
will
be
be
called
called
every
every
time
time
the
the
observable
observable
emits
emits
a
a
new
new
value.
value
And
and
this
this
is
is
why
why
they
they
call
call
it
it
reactive
reactive
programming
programming
because
because
with
with
your
your
subscription,
subscription
And
and
you're
you're
reacting
reacting
to
to
changes
changes
in
in
the
the
observable
observable
data.
data
Throughout
throughout
this
this
video,
video
I'm
i'm
using
using
my
my
own
own
helper
helper
method
method
called
called
print,
print
which
which
will
will
react
react
to
to
each
each
newly
newly
emitted
emitted
item
item
and
and
print
print
it
it
to
to
the
the
DOM
dom
so
so
we
we
can
can
visualize
visualize
what's
what's
happening
happening
in
in
the
the
observable.
observable
And
and
if
if
we
we
open
open
this
this
in
in
the
the
browser,
browser
you
you
can
can
see
see
we
we
get
get
a
a
b
b
c
c
logged
logged
1
1
after
after
the
the
other.
other
Another
another
important
important
concept
concept
to
to
keep
keep
in
in
mind
mind
is
is
that
that
observables
observables
can
can
be
be
completed,
completed
which
which
means
means
they'll
they'll
be
be
shut
shut
off
off
and
and
no
no
longer
longer
emit
emit
values.
values
If
if
we
we
had
had
observer
observer
complete
complete
and
and
then
then
go
go
back
back
to
to
the
the
browser,
browser
you
you
can
can
see
see
that
that
Only
only
a
a
and
and
b
b
are
are
emitted,
emitted
and
and
that's
that's
because
because
the
the
stream
stream
has
has
been
been
closed.
closed
If
if
you
you
think
think
like
like
a
a
plumber,
plumber
creating
creating
the
the
observable
observable
is
is
like
like
connecting
connecting
a
a
pipe
pipe
to
to
a
a
water
water
source
source
And
and
then
then
subscribing
subscribing
is
is
like
like
opening
opening
the
the
valve
valve
that
that
lets
lets
that
that
water
water
out.
out
RxJS
rxjs
provides
provides
a
a
bunch
bunch
of
of
helper
helper
functions
functions
that
that
make
make
it
it
easier
easier
to
to
create
create
observables.
observables
For
for
example,
example
if
if
we
we
want
want
to
to
just
just
create
create
an
an
observable
observable
of
of
a
a
raw
raw
value,
value
we
we
can
can
use
use
of.
of
This
this
will
will
just
just
take
take
the
the
value
value
that
that
you
you
pass
pass
in
in
and
and
wrap
wrap
it
it
in
in
an
an
observable.
observable
If
if
we
we
subscribe
subscribe
to
to
this,
this
then
then
we'll
we'll
just
just
get
get
hello
hello
printed
printed
out
out
in
in
the
the
console.
console
Now
now
the
the
of
of
function
function
is
is
very
very
easy
easy
to
to
mix
mix
up
up
with
with
the
the
from
from
function,
function
which
which
takes
takes
an
an
array,
array
promise,
promise
or
or
iterable
iterable
and
and
then
then
emits
emits
each
each
individual
individual
item
item
from
from
the
the
observable.
observable
We
we
can
can
see
see
the
the
difference
difference
by
by
passing
passing
in
in
a
a
string,
string
which
which
itself
itself
That's
that's
iterable.
iterable
Instead
instead
of
of
emitting
emitting
the
the
entire
entire
string
string
as
as
one
one
event,
event
it
it
emits
emits
each
each
individual
individual
character
character
in
in
that
that
string.
string
Another
another
thing
thing
we
we
can
can
do
do
is
is
create
create
an
an
observable
observable
from
from
events
events
in
in
the
the
DOM.
dom
Using
using
from
from
event,
event
we
we
first
first
pass
pass
in
in
a
a
DOM
dom
element
element
and
and
then
then
the
the
event
event
that
that
we
we
wanna
wanna
listen
listen
to.
to
If
if
we
we
listen
listen
to
to
clicks
clicks
on
on
the
the
document
document
and
and
subscribe
subscribe
to
to
the
the
observable,
observable
we'll
we'll
get
get
an
an
event
event
every
every
time
time
we
we
click
click
on
on
the
the
page.
page
Another
another
thing
thing
we
we
can
can
do
do
is
is
set
set
up
up
an
an
observable
observable
based
based
on
on
a
a
time
time
interval.
interval
It
it
takes
takes
the
the
number
number
of
of
milliseconds
milliseconds
as
as
its
its
argument
argument
and
and
then
then
will
will
emit
emit
a
a
number
number
each
each
time
time
that
that
interval
interval
passes.
passes
Now
now
Now
now
one
one
thing
thing
that
that
a
a
lot
lot
of
of
people
people
don't
don't
realize
realize
is
is
that
that
RxJS
rxjs
can
can
be
be
synchronous
synchronous
or
or
asynchronous.
asynchronous
And
and
you'll
you'll
probably
probably
never
never
have
have
to
to
do
do
this,
this
but
but
you
you
can
can
control
control
that
that
behavior
behavior
by
by
modifying
modifying
schedulers.
schedulers
If
if
you
you
get
get
lost
lost
in
in
this
this
next
next
example,
example
I
i
would
would
recommend
recommend
watching
watching
my
my
async
async
await
await
video,
video
which
which
will
will
teach
teach
you
you
all
all
about
about
the
the
event
event
loop
loop
in
in
JavaScript.
javascript
Let's
let's
go
go
ahead
ahead
and
and
define
define
a
a
string
string
observable
observable
using
using
of,
of
and
and
then
then
we'll
we'll
just
just
synchronously
synchronously
call
call
our
our
print
print
method
method
with
with
world.
world
In
in
this
this
case,
case
RxJS
rxjs
is
is
going
going
to
to
treat
treat
that
that
observable
observable
as
as
a
a
synchronous
synchronous
value.
value
So
so
the
the
subscription
subscription
will
will
happen
happen
on
on
the
the
main
main
thread.
thread
Therefore,
therefore
we
we
get
get
hello,
hello
world
world
printed
printed
1
1
after
after
the
the
other.
other
You
you
can
can
change
change
this
this
behavior
behavior
by
by
modifying
modifying
the
the
scheduler
scheduler
of
of
the
the
observable.
observable
If
if
we
we
pass
pass
in
in
the
the
async
async
Scheduler,
scheduler
it
it
will
will
emit
emit
the
the
value
value
of
of
the
the
observable
observable
on
on
the
the
next
next
iteration
iteration
of
of
the
the
event
event
loop.
loop
This
this
time
time
in
in
the
the
browser,
browser
we
we
get
get
world
world
hello.
hello
And,
and
again,
again
you'll
you'll
probably
probably
never
never
need
need
to
to
mess
mess
with
with
that,
that
but
but
I
i
just
just
wanna
wanna
give
give
you
you
an
an
idea
idea
of
of
Schedulers
schedulers
do.
do
The
the
next
next
thing
thing
we'll
we'll
do
do
is
is
look
look
at
at
the
the
difference
difference
between
between
hot
hot
and
and
cold
cold
observables.
observables
I
i
don't
don't
really
really
like
like
this
this
terminology,
terminology
and
and
I
i
think
think
the
the
best
best
way
way
to
to
think
think
of
of
it
it
is
is
observables
observables
can
can
have
have
multiple
multiple
subscriptions
subscriptions
whereas
whereas
cold
cold
observables
observables
can
can
only
only
have
have
one
one
subscription.
subscription
Cold
cold
observables
observables
don't
don't
actually
actually
create
create
the
the
underlying
underlying
value
value
until
until
they're
they're
subscribed
subscribed
to.
to
We'll
we'll
go
go
ahead
ahead
and
and
create
create
an
an
observable
observable
from
from
scratch
scratch
and
and
just
just
have
have
it
it
generate
generate
a
a
random
random
number.
number
Now
now
if
if
we
we
subscribe
subscribe
to
to
this
this
observable
observable
twice,
twice
you'll
you'll
see
see
that
that
we
we
get
get
2
2
different
different
random
random
numbers.
numbers
That's
that's
because
because
that
that
create
create
callback
callback
function
function
isn't
isn't
called
called
until
until
the
the
subscription
subscription
is
is
created.
created
But
but
often
often
in
in
the
the
real
real
world,
world
that's
that's
not
not
what
what
you
you
actually
actually
want.
want
A
a
lot
lot
Times
times
RxJS
rxjs
is
is
valuable
valuable
because
because
you
you
can
can
share
share
a
a
value
value
across
across
multiple
multiple
subscribers.
subscribers
If
if
you
you
have
have
an
an
existing
existing
cold
cold
observable,
observable
there
there
are
are
multiple
multiple
ways
ways
to
to
make
make
it
it
hot
hot
or
or
in
in
other
other
words,
words
allow
allow
it
it
to
to
be
be
broadcast
broadcast
to
to
multiple
multiple
subscribers.
subscribers
Now
now
in
in
this
this
example,
example
only
only
the
the
first
first
subscriber
subscriber
will
will
get
get
the
the
actual
actual
value.
value
But
but
what's
what's
often
often
useful
useful
in
in
the
the
real
real
world
world
is
is
to
to
use
use
the
the
share
share
replay
replay
operator,
operator
which
which
will
will
cache
cache
the
the
last
last
value
value
as
as
well.
well
If
if
instead
instead
we
we
pipe
pipe
in
in
share
share
replay
replay
1,
1
you
you
can
can
see
see
that
that
both
both
will
will
get
get
the
the
same
same
random
random
number.
number
Now
now
in
in
my
my
experience,
experience
I'm
i'm
not
not
usually
usually
taking
taking
cold
cold
observables
observables
and
and
making
making
them
them
hot.
hot
Instead,
instead
I'm
i'm
creating
creating
subjects
subjects
or
or
behavior
behavior
subjects.
subjects
You
you
can
can
think
think
of
of
a
a
subject
subject
as
as
a
a
hot
hot
observable,
observable
but
but
it
it
has
has
the
the
added
added
benefit
benefit
of
of
being
being
able
able
to
to
have
have
new
new
values
values
pushed
pushed
to
to
it.
it
In
in
plumbing
plumbing
terms,
terms
it's
it's
more
more
like
like
a
a
pump
pump
where
where
you
you
can
can
add
add
new
new
values
values
to
to
the
the
stream
stream
after
after
it's
it's
been
been
created.
created
We
we
can
can
do
do
this
this
easily
easily
by
by
just
just
instantiating
instantiating
a
a
new
new
subject,
subject
and
and
then
then
we
we
can
can
subscribe
subscribe
to
to
it
it
just
just
like
like
we've
we've
done
done
with
with
our
our
other
other
observables.
observables
What's
what's
unique
unique
about
about
it
it
is
is
that
that
it
it
has
has
a
a
next
next
method
method
that
that
we
we
can
can
call
call
to
to
add
add
new
new
values
values
to
to
the
the
stream.
stream
Now
now
a
a
potential
potential
gotcha
gotcha
with
with
a
a
regular
regular
subject
subject
is
is
that
that
you
you
need
need
to
to
have
have
the
the
subscription
subscription
set
set
up
up
before
before
you
you
start
start
adding
adding
values
values
to
to
it.
it
You
you
can
can
see
see
here
here
in
in
this
this
first
first
example,
example
we
we
subscribe,
subscribe
then
then
we
we
add
add
2
2
new
new
values
values
to
to
it,
it
then
then
we
we
set
set
up
up
a
a
second
second
subscriber.
subscriber
And
and
what
what
you
you
intuitively
intuitively
might
might
think
think
is
is
that
that
both
both
subscribers
subscribers
will
will
get
get
the
the
same
same
values.
values
But
but
that's
that's
not
not
true
true
for
for
the
the
second
second
subscriber,
subscriber
which
which
will
will
get
get
nothing
nothing
because
because
it
it
Subscribe
subscribe
late
late
after
after
the
the
values
values
were
were
already
already
added.
added
And
and
that
that
brings
brings
me
me
to
to
one
one
of
of
the
the
most
most
useful
useful
things
things
in
in
RxJS,
rxjs
which
which
is
is
the
the
behavior
behavior
subject.
subject
It's
it's
similar
similar
to
to
the
the
subject
subject
we
we
just
just
looked
looked
at,
at
except
except
it
it
has
has
the
the
concept
concept
of
of
a
a
current
current
value.
value
This
this
means
means
the
the
last
last
emitted
emitted
value
value
will
will
be
be
cached
cached
similar
similar
to
to
how
how
we
we
set
set
it
it
up
up
with
with
share
share
replay
replay
earlier.
earlier
But
but
most
most
importantly,
importantly
it
it
means
means
that
that
every
every
subscription
subscription
will
will
always
always
receive
receive
a
a
value.
value
Even
even
though
though
our
our
second
second
subscriber
subscriber
came
came
in
in
late,
late
it
it
still
still
gets
gets
the
the
last
last
emitted
emitted
value
value
in
in
the
the
stream.
stream
That
that
tends
tends
to
to
be
be
a
a
very
very
powerful
powerful
feature
feature
when
when
doing
doing
things
things
like
like
state
state
management
management
and
and
front
front
end
end
applications.
applications
At
at
this
this
point,
point
we've
we've
only
only
been
been
talking
talking
about
about
creating
creating
observables.
observables
Now
now
it's
it's
time
time
to
to
look
look
at
at
operators,
operators
which
which
help
help
you
you
control
control
the
the
Flow
flow
of
of
data
data
going
going
through
through
your
your
observables.
observables
There
there
are
are
a
a
ton
ton
of
of
operators
operators
built
built
into
into
RxJS,
rxjs
so
so
we'll
we'll
just
just
look
look
at
at
a
a
handful
handful
of
of
some
some
of
of
the
the
most
most
popular
popular
ones.
ones
First,
first
we'll
we'll
create
create
a
a
source
source
observable
observable
that
that
emits
emits
the
the
integers
integers
1
1
through
through
10.
10
You
you
can
can
compose
compose
multiple
multiple
operators
operators
together
together
by
by
using
using
a
a
pipe.
pipe
And
and
just
just
like
like
it
it
sounds,
sounds
your
your
data
data
will
will
flow
flow
through
through
this
this
pipe
pipe
and
and
then
then
be
be
modified
modified
by
by
each
each
function
function
or
or
operator
operator
in
in
the
the
pipe.
pipe
If
if
we
we
subscribe
subscribe
to
to
the
the
empty
empty
pipe,
pipe
it
it
just
just
emits
emits
the
the
values
values
of
of
1
1
through
through
10.
10
To
to
take
take
the
the
input
input
and
and
simply
simply
transform
transform
it
it
to
to
a
a
new
new
output,
output
you
you
can
can
use
use
the
the
map
map
operator.
operator
For
for
example,
example
we
we
can
can
take
take
each
each
number
number
and
and
then
then
raise
raise
it
it
to
to
the
the
power
power
2.
2
Now
now
the
the
observable
observable
emits
emits
the
the
square
square
of
of
the
the
initial
initial
numbers.
numbers
Another
another
thing
thing
we
we
can
can
do
do
is
is
accumulate
accumulate
values
values
as
as
they
they
flow
flow
through
through
the
the
observable
observable
similar
similar
to
to
array
array
reduce.
reduce
If
if
we
we
wanna
wanna
keep
keep
a
a
running
running
total
total
of
of
all
all
the
the
values
values
that
that
were
were
emitted
emitted
in
in
this
this
observable,
observable
we
we
can
can
use
use
the
the
scan
scan
operator
operator
and
and
then
then
add
add
the
the
current
current
value
value
to
to
the
the
accumulated
accumulated
value.
value
Now
now
each
each
emitted
emitted
value
value
gets
gets
added
added
on
on
top
top
of
of
the
the
previous
previous
one.
one
An
an
important
important
thing
thing
to
to
keep
keep
in
in
mind
mind
here
here
is
is
that
that
the
the
order
order
of
of
operation
operation
matters.
matters
For
for
example,
example
if
if
we
we
move
move
the
the
scan
scan
operator
operator
before
before
the
the
map
map
operator,
operator
we're
we're
going
going
to
to
Different
different
results
results
because
because
the
the
underlying
underlying
math
math
is
is
now
now
different.
different
So
so
that's
that's
how
how
you
you
transform
transform
values.
values
But
but
another
another
useful
useful
operator
operator
is
is
filter
filter
which
which
prevents
prevents
certain
certain
items
items
from
from
being
being
emitted
emitted
in
in
the
the
stream.
stream
For
for
example,
example
if
if
we
we
only
only
want
want
values
values
that
that
are
are
greater
greater
than
than
10,
10
we
we
can
can
use
use
the
the
filter
filter
operator
operator
and
and
that
that
will
will
only
only
emit
emit
values
values
that
that
meet
meet
this
this
condition.
condition
And
and
now
now
we
we
only
only
see
see
values
values
that
that
are
are
greater
greater
than
than
10
10
printed
printed
in
in
the
the
UI.
ui
Another
another
thing
thing
we
we
can
can
do
do
with
with
operators
operators
is
is
tell
tell
the
the
observable
observable
to
to
complete.
complete
For
for
example,
example
if
if
we
we
pipe
pipe
in
in
take
take
3,
3
it
it
will
will
only
only
emit
emit
3
3
values
values
from
from
this
this
observable
observable
then
then
complete
complete
it.
it
The
the
next
next
thing
thing
I
i
wanna
wanna
show
show
you
you
is
is
an
an
operator
operator
called
called
tap,
tap
which
which
allows
allows
you
you
to
to
trigger
trigger
side
side
effects
effects
from
from
inside
inside
the
the
observable
observable
pipe.
pipe
In
in
all
all
the
the
examples
examples
so
so
Far,
far
I've
i've
been
been
printing
printing
values
values
to
to
the
the
screen
screen
by
by
using
using
the
the
callback
callback
in
in
the
the
subscribe
subscribe
method,
method
but
but
that
that
only
only
gives
gives
us
us
access
access
to
to
the
the
value
value
at
at
the
the
end
end
of
of
the
the
pipe.
pipe
Most
most
simple
simple
use
use
case
case
that
that
you'll
you'll
find
find
is
is
just
just
console
console
logging
logging
at
at
different
different
points
points
within
within
the
the
observable
observable
pipe.
pipe
The
the
pipe
pipe
modifies
modifies
things
things
from
from
top
top
to
to
bottom.
bottom
So
so
if
if
we
we
add
add
a
a
tap
tap
to
to
the
the
very
very
beginning,
beginning
it's
it's
going
going
to
to
print
print
the
the
initial
initial
value.
value
And
and
if
if
we
we
map
map
it
it
to
to
something
something
else
else
and
and
add
add
another
another
tap
tap
after
after
that,
that
it's
it's
going
going
to
to
print
print
a
a
different
different
value.
value
And
and
you
you
can
can
use
use
tap
tap
to
to
trigger
trigger
more
more
complex
complex
side
side
effects.
effects
For
for
example,
example
you
you
might
might
want
want
to
to
save
save
a
a
value
value
from
from
the
the
observable
observable
to
to
a
a
back
back
end
end
database.
database
If
if
you're
you're
using
using
something
something
like
like
Firebase,
firebase
bass,
bass
you'll
you'll
probably
probably
wanna
wanna
use
use
an
an
async
async
function.
function
So
so
basically,
basically
it
it
just
just
gives
gives
you
you
a
a
context
context
to
to
tap
tap
into
into
the
the
observable
observable
and
and
do
do
something.
something
Another
another
term
term
you
you
might
might
hear
hear
with
with
RxJS
rxjs
is
is
backpressure.
backpressure
And,
and
basically,
basically
that
that
means
means
you
you
have
have
an
an
observable
observable
that's
that's
emitting
emitting
way
way
more
more
values
values
than
than
you
you
actually
actually
need.
need
We
we
can
can
simulate
simulate
this
this
in
in
the
the
code
code
by
by
listening
listening
to
to
the
the
mouse
mouse
move
move
event
event
on
on
the
the
DOM.
dom
Moving
moving
the
the
mouse
mouse
across
across
the
the
screen
screen
will
will
cause
cause
the
the
observable
observable
to
to
emit
emit
multiple
multiple
events
events
every
every
second.
second
RXJS
rxjs
has
has
several
several
operators
operators
that
that
can
can
help
help
us
us
with
with
this
this
situation.
situation
The
the
first
first
strategy
strategy
we'll
we'll
look
look
at
at
is
is
to
to
debounce
debounce
the
the
events.
events
A
a
debounce
debounce
will
will
filter
filter
out
out
all
all
events
events
until
until
they
they
have
have
stopped
stopped
happening
happening
for
for
a
a
certain
certain
period
period
of
of
time,
time
in
in
this
this
case,
case
a
a
1000
1000
milliseconds.
milliseconds
A
a
debounce
debounce
is
is
really
really
useful
useful
for
for
something
something
like
like
a
a
type
type
ahead
ahead
where
where
you
you
don't
don't
wanna
wanna
make
make
an
an
API
api
call
call
until
until
the
the
user
user
is
is
done
done
typing.
typing
You
you
can
can
see
see
here
here
if
if
we
we
mouse
mouse
around
around
for
for
a
a
little
little
while,
while
nothing
nothing
happens.
happens
Then
then
if
if
we
we
stop,
stop
Our
our
event
event
will
will
be
be
emitted
emitted
after
after
one
one
second.
second
An
an
alternative
alternative
to
to
a
a
debounce
debounce
is
is
a
a
throttle.
throttle
It
it
will
will
emit
emit
the
the
first
first
value,
value
but
but
make
make
sure
sure
that
that
no
no
additional
additional
values
values
can
can
be
be
emitted
emitted
until
until
a
a
certain
certain
time
time
period
period
has
has
passed.
passed
We
we
go
go
back
back
to
to
the
the
demo
demo
and
and
start
start
moving
moving
around,
around
at
at
the
the
very
very
most,
most
we'll
we'll
get
get
one
one
event
event
emitted
emitted
per
per
second.
second
These
these
operators
operators
are
are
alleviating
alleviating
the
the
back
back
pressure,
pressure
but
but
they're
they're
also
also
filtering
filtering
out
out
a
a
lot
lot
of
of
data.
data
If
if
we
we
want
want
to
to
keep
keep
all
all
the
the
data
data
but
but
just
just
not
not
listen
listen
to
to
it
it
all
all
at
at
once,
once
we
we
can
can
use
use
a
a
buffer.
buffer
This
this
will
will
collect
collect
all
all
the
the
events
events
into
into
an
an
array
array
and
and
then
then
only
only
emit
emit
them
them
when
when
they
they
get
get
to
to
a
a
length
length
of
of
20.
20
Now
now
we're
we're
going
going
to
to
switch
switch
gears
gears
to
to
another
another
very
very
important
important
operator
operator
called
called
switch
switch
map.
map
This
this
allows
allows
you
you
to
to
start
start
with
with
one
one
observable
observable
and
and
then
then
switch
switch
to
to
another
another
one,
one
which
which
is
is
very
very
important
important
when
when
we're
we're
talking
talking
about
about
data.
data
For
for
example,
example
if
if
you're
you're
a
a
Firebase
firebase
user,
user
you
you
probably
probably
have
have
an
an
observable
observable
of
of
a
a
user
user
logged
logged
into
into
your
your
app,
app
and
and
then
then
you
you
might
might
want
want
to
to
switch
switch
to
to
another
another
observable
observable
of
of
Some
some
information
information
about
about
that
that
user
user
in
in
the
the
database.
database
We
we
can
can
simulate
simulate
that
that
in
in
our
our
code
code
by
by
creating
creating
an
an
observable
observable
of
of
an
an
object,
object
and
and
then
then
I'll
i'll
create
create
a
a
function
function
that
that
returns
returns
an
an
observable
observable
of
of
Some
some
information
information
based
based
on
on
a
a
user
user
ID.
id
We
we
can't
can't
call
call
this
this
function
function
until
until
we
we
have
have
a
a
user
user
ID.
id
So
so
the
the
question
question
becomes,
becomes
how
how
do
do
we
we
get
get
the
the
user
user
ID
id
out
out
of
of
the
the
observable?
observable
The
the
naive
naive
way
way
to
to
do
do
this
this
is
is
to
to
nest
nest
subscriptions
subscriptions
within
within
each
each
other.
other
So
so
first,
first
we
we
subscribe
subscribe
to
to
the
the
user.
user
That'll
that'll
give
give
us
us
the
the
user
user
ID.
id
Then
then
we
we
create
create
another
another
description
description
inside
inside
of
of
that
that
callback
callback
for
for
the
the
orders.
orders
That
that
code
code
will
will
actually
actually
work,
work
but
but
there's
there's
a
a
better
better
way
way
to
to
do
do
this.
this
Instead,
instead
we'll
we'll
start
start
with
with
our
our
user
user
observable
observable
To
to
compose
compose
a
a
new
new
observable
observable
called
called
orders,
orders
we
we
first
first
add
add
a
a
pipe
pipe
to
to
the
the
user
user
and
and
then
then
we
we
use
use
the
the
switch
switch
map
map
operator,
operator
which
which
will
will
give
give
us
us
access
access
to
to
the
the
user
user
ID.
id
And
and
then
then
we
we
just
just
return
return
an
an
observable
observable
from
from
it,
it
and
and
you
you
can
can
also
also
return
return
a
a
promise
promise
or
or
an
an
array
array
here
here
as
as
well.
well
So
so
if
if
you
you
ever
ever
have
have
one
one
value
value
that
that
depends
depends
on
on
another
another
value,
value
switch
switch
map
map
might
might
be
be
the
the
operator
operator
that
that
you're
you're
looking
looking
for.
for
But
but
there
there
might
might
be
be
other
other
cases
cases
where
where
you
you
have
have
multiple
multiple
observables
observables
that
that
you
you
just
just
want
want
to
to
combine
combine
into
into
a
a
single
single
stream.
stream
We'll
we'll
look
look
at
at
2
2
different
different
functions
functions
here
here
called
called
combine
combine
latest
latest
and
and
merge.
merge
And
and
keep
keep
in
in
mind
mind
these
these
are
are
not
not
technically
technically
operators,
operators
so
so
we
we
import
import
them
them
directly
directly
from
from
RxJS.
rxjs
I'm
i'm
creating
creating
a
a
cold
cold
observable
observable
of
of
a
a
random
random
number
number
then
then
I'm
i'm
creating
creating
a
a
second
second
observable
observable
that
that
just
just
adds
adds
a
a
delay
delay
to
to
that
that
random
random
number.
number
1st,
1st
we'll
we'll
use
use
combine
combine
latest
latest
and
and
it
it
takes
takes
an
an
array
array
of
of
observables
observables
And
and
it
it
will
will
wait
wait
for
for
each
each
observable
observable
to
to
emit
emit
a
a
value
value
and
and
then
then
emit
emit
everything
everything
together
together
as
as
an
an
array.
array
Even
even
though
though
the
the
random
random
numbers
numbers
are
are
going
going
to
to
emit
emit
something
something
right
right
away,
away
going
going
to
to
wait
wait
for
for
that
that
delay
delay
to
to
resolve
resolve
into
into
a
a
value
value
before
before
it
it
emits
emits
anything.
anything
Then
then
if
if
any
any
of
of
the
the
observables
observables
emit
emit
anything
anything
after
after
that,
that
it
it
will
will
emit
emit
everything
everything
again
again
as
as
an
an
array.
array
In
in
other
other
words,
words
it
it
gives
gives
you
you
the
the
current
current
state
state
of
of
every
every
observable
observable
in
in
this
this
array.
array
So
so
initially,
initially
it's
it's
blank
blank
for
for
one
one
second
second
waiting
waiting
for
for
that
that
delay
delay
and
and
then
then
it
it
emits
emits
out
out
the
the
4
4
random
random
numbers.
numbers
In
in
many
many
cases,
cases
though,
though
you
you
don't
don't
want
want
to
to
wait
wait
for
for
that
that
delay.
delay
So
so
instead,
instead
you
you
can
can
use
use
merge
merge
which
which
will
will
just
just
emit
emit
each
each
value
value
1
1
by
by
1
1
as
as
it
it
comes
comes
in
in
through
through
the
the
stream.
stream
Merge
merge
doesn't
doesn't
care
care
about
about
the
the
array
array
position
position
of
of
the
the
observable.
observable
It
it
only
only
cares
cares
about
about
when
when
it
it
emits
emits
it
it
in
in
the
the
context
context
of
of
time.
time
So
so
it
it
emits
emits
the
the
first
first
three
three
values
values
and
and
then
then
the
the
delayed
delayed
value
value
a
a
second
second
later.
later
Another
another
thing
thing
you
you
might
might
be
be
wondering
wondering
is
is
how
how
to
to
catch
catch
errors
errors
in
in
the
the
context
context
of
of
a
a
stream.
stream
You
you
have
have
a
a
lot
lot
of
of
flexibility
flexibility
here,
here
but
but
one
one
of
of
the
the
most
most
common
common
strategies
strategies
is
is
to
to
catch
catch
the
the
error
error
and
and
then
then
replace
replace
it
it
with
with
some
some
other
other
value.
value
We
we
can
can
do
do
this
this
easily
easily
with
with
the
the
catch
catch
error
error
operator.
operator
It
it
can
can
intercept
intercept
the
the
error
error
and
and
then
then
emit
emit
some
some
other
other
default
default
value
value
out
out
of
of
the
the
stream.
stream
And
and
one
one
thing
thing
that's
that's
really
really
nice
nice
about
about
RxJS
rxjs
is
is
you
you
can
can
easily
easily
retry
retry
Try
try
things
things
by
by
just
just
piping
piping
in
in
the
the
retry
retry
operator.
operator
I'm
i'm
not
not
going
going
to
to
get
get
into
into
it
it
here,
here
but
but
it's
it's
super
super
useful
useful
when
when
working
working
with
with
HTTP
http
calls.
calls
1st,
1st
I'll
i'll
push
push
a
a
regular
regular
value
value
and
and
then
then
an
an
error
error
to
to
the
the
subject.
subject
If
if
we
we
don't
don't
catch
catch
the
the
error,
error
we'll
we'll
get
get
this
this
uncaught
uncaught
error
error
in
in
the
the
console.
console
But
but
by
by
using
using
the
the
catch
catch
error
error
operator,
operator
we
we
can
can
handle
handle
it
it
in
in
the
the
background
background
and
and
then
then
provide
provide
some
some
useful
useful
information
information
to
to
the
the
user
user
in
in
the
the
front
front
end.
end
Now
now
if
if
you're
you're
a
a
good
good
plumber,
plumber
then
then
you
you
shouldn't
shouldn't
have
have
pipes
pipes
that
that
leak.
leak
And
and
by
by
that,
that
I'm
i'm
talking
talking
about
about
memory
memory
leaks.
leaks
There
there
are
are
2
2
main
main
ways
ways
to
to
prevent
prevent
memory
memory
leaks
leaks
with
with
RxJS.
rxjs
The
the
first
first
way
way
is
is
to
to
unsubscribe
unsubscribe
from
from
your
your
subscriptions.
subscriptions
Take,
take
for
for
example,
example
this
this
interval.
interval
This
this
interval
interval
is
is
going
going
to
to
run
run
forever.
forever
So
so
if
if
we
we
don't
don't
close
close
the
the
subscription,
subscription
it's
it's
just
just
going
going
to
to
create
create
a
a
memory
memory
leak
leak
in
in
the
the
background.
background
One
one
potential
potential
way
way
to
to
handle
handle
this
this
is
is
to
to
create
create
a
a
variable
variable
for
for
the
the
subscription
subscription
and
and
then
then
call
call
subscription
subscription
unsubscribe
unsubscribe
at
at
some
some
other
other
point
point
in
in
the
the
code.
code
This
this
will
will
stop
stop
the
the
leak
leak
because
because
we
we
can
can
see
see
here
here
the
the
observable
observable
only
only
emits
emits
10
10
values,
values
but
but
there's
there's
actually
actually
a
a
better
better
way
way
we
we
can
can
do
do
this.
this
We
we
can
can
pipe
pipe
in
in
the
the
take
take
while
while
operator
operator
to
to
the
the
interval
interval
itself
itself
And
and
that
that
will
will
tell
tell
it
it
to
to
emit
emit
values
values
only
only
while
while
a
a
certain
certain
condition
condition
is
is
true.
true
When
when
that
that
condition
condition
becomes
becomes
false,
false
it
it
will
will
stop
stop
emitting
emitting
values,
values
therefore,
therefore
preventing
preventing
the
the
memory
memory
leak.
leak
And
and
we
we
don't
don't
need
need
to
to
manually
manually
unsubscribe
unsubscribe
anywhere
anywhere
in
in
our
our
code.
code
That
that
works
works
well
well
in
in
a
a
lot
lot
of
of
situations,
situations
but
but
sometimes
sometimes
you
you
want
want
some
some
other
other
observable
observable
or
or
subject
subject
to
to
be
be
the
the
thing
thing
that
that
triggers
triggers
the
the
subscription
subscription
to
to
stop.
stop
For
for
that,
that
we
we
have
have
the
the
take
take
and
and
tell
tell
operator
operator
and
and
it
it
takes
takes
an
an
observable
observable
as
as
its
its
argument.
argument
And
and
when
when
that
that
observable
observable
emits
emits
something,
something
it
it
will
will
cancel
cancel
the
the
subscription
subscription
on
on
the
the
source.
source
For
for
example,
example
if
if
we
we
wanted
wanted
to
to
set
set
a
a
timer
timer
for
for
2
2
2nd
2nd
on
on
this
this
interval,
interval
we
we
could
could
do
do
that
that
by
by
using
using
take
take
and
and
tell
tell
with
with
a
a
timer
timer
observable.
observable
When
when
the
the
timer
timer
finishes
finishes
it
it
will
will
complete
complete
the
the
interval
interval
and
and
then
then
end
end
the
the
subscription.
subscription
Gonna
gonna
go
go
ahead
ahead
and
and
wrap
wrap
things
things
up
up
there.
there
We
we
barely
barely
just
just
scratched
scratched
the
the
surface
surface
with
with
RXJS,
rxjs
so
so
let
let
me
me
know
know
what
what
you
you
wanna
wanna
see
see
next
next
in
in
the
the
comments.
comments
If
if
this
this
video
video
helped
helped
you,
you
please
please
like
like
and
and
subscribe.
subscribe
Thanks
thanks
for
for
watching
watching
and
and
I
i
will
will
talk
talk
to
to
you
you
soon.
soon
success
RxJS is a tool for managing data streams and allows users to create new events and variables. It can be used for subscription and the use of a helper method to create-only variables. The speakers explain how to use RxJS for database and data warehouses, including creating subscriptions and fixing errors in the database, and how to prevent memory leaks through subscriptions and the use of a take/ Association operator. They also offer a recommendation for a future video and encourage viewers to like and subscribe.
RxJS Top Ten - Code This, Not That
One of the most difficult but also most rewarding JavaScript libraries to learn is RxJS. It's a tool that helps us control data as it flows through the dimension of Time. In today's episode of Code This Not That, you'll learn 10 fundamental concepts in RxJS and how to avoid the bad stuff. If you're new here, like and Subscribe and leave me a comment below for a chance to win this t shirt next week. Arc's JS is getting pretty popular these days. In fact, it gets more daily NPM PM downloads, then Angular, React, and Vue. And the only functional library that I'm aware of that's bigger is Lodash. And the reason it's so popular is because JavaScript alone doesn't give us quite everything We would like to work with asynchronous streams of data. We have promises, but they only work with a single async value. So we use callbacks for real time streams, but you've probably heard the term callback help. RxJS addresses these issues and gives us a powerful functional library for dealing with streams. And when I say stream, I'm talking about any data source that unfolds over the dimension of time, Things like data from Firebase, DOM events, WebSockets, file uploads, etcetera. The first thing you'll need to do is install RxJS. I'm currently running version 6.4. Now I'm just using vanilla JavaScript with Webpack, but feel free to follow along with your favorite JavaScript framework. The most fundamental class in RxJS is the observable. You can think of it as a wrapper for some data that can be subscribed to, and then the subscriber will be notified anytime the data changes. When working with RxJS, you should think of yourself as a plumber. And I mean that in the most literal sense because an observable is essentially a pipe for data and RxJS gives you all kinds of tools to modify those pipes. Let's go ahead and create our first observable, but first we need to import the RxJS library, and there's a right and a wrong way to do this. Currently, I'm doing it the wrong way by using import star as RX, but that's going to cause the entire library to be bundled up in our code. You can see down here we have a bundle size of 47 kilobytes, but RxJS is a tree shakeable library, which means we only have to import the code that we actually need. So when working with RxJS, you should only import the classes and operators that you actually need in your source code. And by doing that, we reduce our bundle size to less than 2 kilobytes. Now that you know that, let's go ahead and create an observable from scratch. Now you won't normally create observables like this in your own code, but it's a good exercise to understand what an observable is. When we call observable create, it gives us a callback function that we can use to notify a subscriber with some new data. This can be synchronous or asynchronous. But, basically, every time we call next, it's like emitting an event to the subscriber that they can listen to and react to. Now that we have our observable created, we can create to that observable by calling subscribe on it. Subscribe takes a function that will be called every time the observable emits a new value. And this is why they call it reactive programming because with your subscription, And you're reacting to changes in the observable data. Throughout this video, I'm using my own helper method called print, which will react to each newly emitted item and print it to the DOM so we can visualize what's happening in the observable. And if we open this in the browser, you can see we get a b c logged 1 after the other. Another important concept to keep in mind is that observables can be completed, which means they'll be shut off and no longer emit values. If we had observer complete and then go back to the browser, you can see that Only a and b are emitted, and that's because the stream has been closed. If you think like a plumber, creating the observable is like connecting a pipe to a water source And then subscribing is like opening the valve that lets that water out. RxJS provides a bunch of helper functions that make it easier to create observables. For example, if we want to just create an observable of a raw value, we can use of. This will just take the value that you pass in and wrap it in an observable. If we subscribe to this, then we'll just get hello printed out in the console. Now the of function is very easy to mix up with the from function, which takes an array, promise, or iterable and then emits each individual item from the observable. We can see the difference by passing in a string, which itself That's iterable. Instead of emitting the entire string as one event, it emits each individual character in that string. Another thing we can do is create an observable from events in the DOM. Using from event, we first pass in a DOM element and then the event that we wanna listen to. If we listen to clicks on the document and subscribe to the observable, we'll get an event every time we click on the page. Another thing we can do is set up an observable based on a time interval. It takes the number of milliseconds as its argument and then will emit a number each time that interval passes. Now Now one thing that a lot of people don't realize is that RxJS can be synchronous or asynchronous. And you'll probably never have to do this, but you can control that behavior by modifying schedulers. If you get lost in this next example, I would recommend watching my async await video, which will teach you all about the event loop in JavaScript. Let's go ahead and define a string observable using of, and then we'll just synchronously call our print method with world. In this case, RxJS is going to treat that observable as a synchronous value. So the subscription will happen on the main thread. Therefore, we get hello, world printed 1 after the other. You can change this behavior by modifying the scheduler of the observable. If we pass in the async Scheduler, it will emit the value of the observable on the next iteration of the event loop. This time in the browser, we get world hello. And, again, you'll probably never need to mess with that, but I just wanna give you an idea of Schedulers do. The next thing we'll do is look at the difference between hot and cold observables. I don't really like this terminology, and I think the best way to think of it is observables can have multiple subscriptions whereas cold observables can only have one subscription. Cold observables don't actually create the underlying value until they're subscribed to. We'll go ahead and create an observable from scratch and just have it generate a random number. Now if we subscribe to this observable twice, you'll see that we get 2 different random numbers. That's because that create callback function isn't called until the subscription is created. But often in the real world, that's not what you actually want. A lot Times RxJS is valuable because you can share a value across multiple subscribers. If you have an existing cold observable, there are multiple ways to make it hot or in other words, allow it to be broadcast to multiple subscribers. Now in this example, only the first subscriber will get the actual value. But what's often useful in the real world is to use the share replay operator, which will cache the last value as well. If instead we pipe in share replay 1, you can see that both will get the same random number. Now in my experience, I'm not usually taking cold observables and making them hot. Instead, I'm creating subjects or behavior subjects. You can think of a subject as a hot observable, but it has the added benefit of being able to have new values pushed to it. In plumbing terms, it's more like a pump where you can add new values to the stream after it's been created. We can do this easily by just instantiating a new subject, and then we can subscribe to it just like we've done with our other observables. What's unique about it is that it has a next method that we can call to add new values to the stream. Now a potential gotcha with a regular subject is that you need to have the subscription set up before you start adding values to it. You can see here in this first example, we subscribe, then we add 2 new values to it, then we set up a second subscriber. And what you intuitively might think is that both subscribers will get the same values. But that's not true for the second subscriber, which will get nothing because it Subscribe late after the values were already added. And that brings me to one of the most useful things in RxJS, which is the behavior subject. It's similar to the subject we just looked at, except it has the concept of a current value. This means the last emitted value will be cached similar to how we set it up with share replay earlier. But most importantly, it means that every subscription will always receive a value. Even though our second subscriber came in late, it still gets the last emitted value in the stream. That tends to be a very powerful feature when doing things like state management and front end applications. At this point, we've only been talking about creating observables. Now it's time to look at operators, which help you control the Flow of data going through your observables. There are a ton of operators built into RxJS, so we'll just look at a handful of some of the most popular ones. First, we'll create a source observable that emits the integers 1 through 10. You can compose multiple operators together by using a pipe. And just like it sounds, your data will flow through this pipe and then be modified by each function or operator in the pipe. If we subscribe to the empty pipe, it just emits the values of 1 through 10. To take the input and simply transform it to a new output, you can use the map operator. For example, we can take each number and then raise it to the power 2. Now the observable emits the square of the initial numbers. Another thing we can do is accumulate values as they flow through the observable similar to array reduce. If we wanna keep a running total of all the values that were emitted in this observable, we can use the scan operator and then add the current value to the accumulated value. Now each emitted value gets added on top of the previous one. An important thing to keep in mind here is that the order of operation matters. For example, if we move the scan operator before the map operator, we're going to Different results because the underlying math is now different. So that's how you transform values. But another useful operator is filter which prevents certain items from being emitted in the stream. For example, if we only want values that are greater than 10, we can use the filter operator and that will only emit values that meet this condition. And now we only see values that are greater than 10 printed in the UI. Another thing we can do with operators is tell the observable to complete. For example, if we pipe in take 3, it will only emit 3 values from this observable then complete it. The next thing I wanna show you is an operator called tap, which allows you to trigger side effects from inside the observable pipe. In all the examples so Far, I've been printing values to the screen by using the callback in the subscribe method, but that only gives us access to the value at the end of the pipe. Most simple use case that you'll find is just console logging at different points within the observable pipe. The pipe modifies things from top to bottom. So if we add a tap to the very beginning, it's going to print the initial value. And if we map it to something else and add another tap after that, it's going to print a different value. And you can use tap to trigger more complex side effects. For example, you might want to save a value from the observable to a back end database. If you're using something like Firebase, bass, you'll probably wanna use an async function. So basically, it just gives you a context to tap into the observable and do something. Another term you might hear with RxJS is backpressure. And, basically, that means you have an observable that's emitting way more values than you actually need. We can simulate this in the code by listening to the mouse move event on the DOM. Moving the mouse across the screen will cause the observable to emit multiple events every second. RXJS has several operators that can help us with this situation. The first strategy we'll look at is to debounce the events. A debounce will filter out all events until they have stopped happening for a certain period of time, in this case, a 1000 milliseconds. A debounce is really useful for something like a type ahead where you don't wanna make an API call until the user is done typing. You can see here if we mouse around for a little while, nothing happens. Then if we stop, Our event will be emitted after one second. An alternative to a debounce is a throttle. It will emit the first value, but make sure that no additional values can be emitted until a certain time period has passed. We go back to the demo and start moving around, at the very most, we'll get one event emitted per second. These operators are alleviating the back pressure, but they're also filtering out a lot of data. If we want to keep all the data but just not listen to it all at once, we can use a buffer. This will collect all the events into an array and then only emit them when they get to a length of 20. Now we're going to switch gears to another very important operator called switch map. This allows you to start with one observable and then switch to another one, which is very important when we're talking about data. For example, if you're a Firebase user, you probably have an observable of a user logged into your app, and then you might want to switch to another observable of Some information about that user in the database. We can simulate that in our code by creating an observable of an object, and then I'll create a function that returns an observable of Some information based on a user ID. We can't call this function until we have a user ID. So the question becomes, how do we get the user ID out of the observable? The naive way to do this is to nest subscriptions within each other. So first, we subscribe to the user. That'll give us the user ID. Then we create another description inside of that callback for the orders. That code will actually work, but there's a better way to do this. Instead, we'll start with our user observable To compose a new observable called orders, we first add a pipe to the user and then we use the switch map operator, which will give us access to the user ID. And then we just return an observable from it, and you can also return a promise or an array here as well. So if you ever have one value that depends on another value, switch map might be the operator that you're looking for. But there might be other cases where you have multiple observables that you just want to combine into a single stream. We'll look at 2 different functions here called combine latest and merge. And keep in mind these are not technically operators, so we import them directly from RxJS. I'm creating a cold observable of a random number then I'm creating a second observable that just adds a delay to that random number. 1st, we'll use combine latest and it takes an array of observables And it will wait for each observable to emit a value and then emit everything together as an array. Even though the random numbers are going to emit something right away, going to wait for that delay to resolve into a value before it emits anything. Then if any of the observables emit anything after that, it will emit everything again as an array. In other words, it gives you the current state of every observable in this array. So initially, it's blank for one second waiting for that delay and then it emits out the 4 random numbers. In many cases, though, you don't want to wait for that delay. So instead, you can use merge which will just emit each value 1 by 1 as it comes in through the stream. Merge doesn't care about the array position of the observable. It only cares about when it emits it in the context of time. So it emits the first three values and then the delayed value a second later. Another thing you might be wondering is how to catch errors in the context of a stream. You have a lot of flexibility here, but one of the most common strategies is to catch the error and then replace it with some other value. We can do this easily with the catch error operator. It can intercept the error and then emit some other default value out of the stream. And one thing that's really nice about RxJS is you can easily retry Try things by just piping in the retry operator. I'm not going to get into it here, but it's super useful when working with HTTP calls. 1st, I'll push a regular value and then an error to the subject. If we don't catch the error, we'll get this uncaught error in the console. But by using the catch error operator, we can handle it in the background and then provide some useful information to the user in the front end. Now if you're a good plumber, then you shouldn't have pipes that leak. And by that, I'm talking about memory leaks. There are 2 main ways to prevent memory leaks with RxJS. The first way is to unsubscribe from your subscriptions. Take, for example, this interval. This interval is going to run forever. So if we don't close the subscription, it's just going to create a memory leak in the background. One potential way to handle this is to create a variable for the subscription and then call subscription unsubscribe at some other point in the code. This will stop the leak because we can see here the observable only emits 10 values, but there's actually a better way we can do this. We can pipe in the take while operator to the interval itself And that will tell it to emit values only while a certain condition is true. When that condition becomes false, it will stop emitting values, therefore, preventing the memory leak. And we don't need to manually unsubscribe anywhere in our code. That works well in a lot of situations, but sometimes you want some other observable or subject to be the thing that triggers the subscription to stop. For that, we have the take and tell operator and it takes an observable as its argument. And when that observable emits something, it will cancel the subscription on the source. For example, if we wanted to set a timer for 2 2nd on this interval, we could do that by using take and tell with a timer observable. When the timer finishes it will complete the interval and then end the subscription. Gonna go ahead and wrap things up there. We barely just scratched the surface with RXJS, so let me know what you wanna see next in the comments. If this video helped you, please like and subscribe. Thanks for watching and I will talk to you soon.
RxJS is a tool for managing data streams and allows users to create new events and variables. It can be used for subscription and the use of a helper method to create-only variables. The speakers explain how to use RxJS for database and data warehouses, including creating subscriptions and fixing errors in the database, and how to prevent memory leaks through subscriptions and the use of a take/ Association operator. They also offer a recommendation for a future video and encourage viewers to like and subscribe.

        [INST]
        You are youtuber called Fireship you make engaging high-intensity and entertaining coding tutorials and tech news. 
        you covers a wide range of topics relevant to programmers, aiming to help them learn and improve their skills quickly.
        
        Given the title of the video : RxJS Top Ten - Code This, Not That 
        and a small summary : RxJS is a tool for managing data streams and allows users to create new events and variables. It can be used for subscription and the use of a helper method to create-only variables. The speakers explain how to use RxJS for database and data warehouses, including creating subscriptions and fixing errors in the database, and how to prevent memory leaks through subscriptions and the use of a take/ Association operator. They also offer a recommendation for a future video and encourage viewers to like and subscribe.
        [/INST]
        
        Generate the video : One of the most difficult but also most rewarding JavaScript libraries to learn is RxJS. It's a tool that helps us control data as it flows through the dimension of Time. In today's episode of Code This Not That, you'll learn 10 fundamental concepts in RxJS and how to avoid the bad stuff. If you're new here, like and Subscribe and leave me a comment below for a chance to win this t shirt next week. Arc's JS is getting pretty popular these days. In fact, it gets more daily NPM PM downloads, then Angular, React, and Vue. And the only functional library that I'm aware of that's bigger is Lodash. And the reason it's so popular is because JavaScript alone doesn't give us quite everything We would like to work with asynchronous streams of data. We have promises, but they only work with a single async value. So we use callbacks for real time streams, but you've probably heard the term callback help. RxJS addresses these issues and gives us a powerful functional library for dealing with streams. And when I say stream, I'm talking about any data source that unfolds over the dimension of time, Things like data from Firebase, DOM events, WebSockets, file uploads, etcetera. The first thing you'll need to do is install RxJS. I'm currently running version 6.4. Now I'm just using vanilla JavaScript with Webpack, but feel free to follow along with your favorite JavaScript framework. The most fundamental class in RxJS is the observable. You can think of it as a wrapper for some data that can be subscribed to, and then the subscriber will be notified anytime the data changes. When working with RxJS, you should think of yourself as a plumber. And I mean that in the most literal sense because an observable is essentially a pipe for data and RxJS gives you all kinds of tools to modify those pipes. Let's go ahead and create our first observable, but first we need to import the RxJS library, and there's a right and a wrong way to do this. Currently, I'm doing it the wrong way by using import star as RX, but that's going to cause the entire library to be bundled up in our code. You can see down here we have a bundle size of 47 kilobytes, but RxJS is a tree shakeable library, which means we only have to import the code that we actually need. So when working with RxJS, you should only import the classes and operators that you actually need in your source code. And by doing that, we reduce our bundle size to less than 2 kilobytes. Now that you know that, let's go ahead and create an observable from scratch. Now you won't normally create observables like this in your own code, but it's a good exercise to understand what an observable is. When we call observable create, it gives us a callback function that we can use to notify a subscriber with some new data. This can be synchronous or asynchronous. But, basically, every time we call next, it's like emitting an event to the subscriber that they can listen to and react to. Now that we have our observable created, we can create to that observable by calling subscribe on it. Subscribe takes a function that will be called every time the observable emits a new value. And this is why they call it reactive programming because with your subscription, And you're reacting to changes in the observable data. Throughout this video, I'm using my own helper method called print, which will react to each newly emitted item and print it to the DOM so we can visualize what's happening in the observable. And if we open this in the browser, you can see we get a b c logged 1 after the other. Another important concept to keep in mind is that observables can be completed, which means they'll be shut off and no longer emit values. If we had observer complete and then go back to the browser, you can see that Only a and b are emitted, and that's because the stream has been closed. If you think like a plumber, creating the observable is like connecting a pipe to a water source And then subscribing is like opening the valve that lets that water out. RxJS provides a bunch of helper functions that make it easier to create observables. For example, if we want to just create an observable of a raw value, we can use of. This will just take the value that you pass in and wrap it in an observable. If we subscribe to this, then we'll just get hello printed out in the console. Now the of function is very easy to mix up with the from function, which takes an array, promise, or iterable and then emits each individual item from the observable. We can see the difference by passing in a string, which itself That's iterable. Instead of emitting the entire string as one event, it emits each individual character in that string. Another thing we can do is create an observable from events in the DOM. Using from event, we first pass in a DOM element and then the event that we wanna listen to. If we listen to clicks on the document and subscribe to the observable, we'll get an event every time we click on the page. Another thing we can do is set up an observable based on a time interval. It takes the number of milliseconds as its argument and then will emit a number each time that interval passes. Now Now one thing that a lot of people don't realize is that RxJS can be synchronous or asynchronous. And you'll probably never have to do this, but you can control that behavior by modifying schedulers. If you get lost in this next example, I would recommend watching my async await video, which will teach you all about the event loop in JavaScript. Let's go ahead and define a string observable using of, and then we'll just synchronously call our print method with world. In this case, RxJS is going to treat that observable as a synchronous value. So the subscription will happen on the main thread. Therefore, we get hello, world printed 1 after the other. You can change this behavior by modifying the scheduler of the observable. If we pass in the async Scheduler, it will emit the value of the observable on the next iteration of the event loop. This time in the browser, we get world hello. And, again, you'll probably never need to mess with that, but I just wanna give you an idea of Schedulers do. The next thing we'll do is look at the difference between hot and cold observables. I don't really like this terminology, and I think the best way to think of it is observables can have multiple subscriptions whereas cold observables can only have one subscription. Cold observables don't actually create the underlying value until they're subscribed to. We'll go ahead and create an observable from scratch and just have it generate a random number. Now if we subscribe to this observable twice, you'll see that we get 2 different random numbers. That's because that create callback function isn't called until the subscription is created. But often in the real world, that's not what you actually want. A lot Times RxJS is valuable because you can share a value across multiple subscribers. If you have an existing cold observable, there are multiple ways to make it hot or in other words, allow it to be broadcast to multiple subscribers. Now in this example, only the first subscriber will get the actual value. But what's often useful in the real world is to use the share replay operator, which will cache the last value as well. If instead we pipe in share replay 1, you can see that both will get the same random number. Now in my experience, I'm not usually taking cold observables and making them hot. Instead, I'm creating subjects or behavior subjects. You can think of a subject as a hot observable, but it has the added benefit of being able to have new values pushed to it. In plumbing terms, it's more like a pump where you can add new values to the stream after it's been created. We can do this easily by just instantiating a new subject, and then we can subscribe to it just like we've done with our other observables. What's unique about it is that it has a next method that we can call to add new values to the stream. Now a potential gotcha with a regular subject is that you need to have the subscription set up before you start adding values to it. You can see here in this first example, we subscribe, then we add 2 new values to it, then we set up a second subscriber. And what you intuitively might think is that both subscribers will get the same values. But that's not true for the second subscriber, which will get nothing because it Subscribe late after the values were already added. And that brings me to one of the most useful things in RxJS, which is the behavior subject. It's similar to the subject we just looked at, except it has the concept of a current value. This means the last emitted value will be cached similar to how we set it up with share replay earlier. But most importantly, it means that every subscription will always receive a value. Even though our second subscriber came in late, it still gets the last emitted value in the stream. That tends to be a very powerful feature when doing things like state management and front end applications. At this point, we've only been talking about creating observables. Now it's time to look at operators, which help you control the Flow of data going through your observables. There are a ton of operators built into RxJS, so we'll just look at a handful of some of the most popular ones. First, we'll create a source observable that emits the integers 1 through 10. You can compose multiple operators together by using a pipe. And just like it sounds, your data will flow through this pipe and then be modified by each function or operator in the pipe. If we subscribe to the empty pipe, it just emits the values of 1 through 10. To take the input and simply transform it to a new output, you can use the map operator. For example, we can take each number and then raise it to the power 2. Now the observable emits the square of the initial numbers. Another thing we can do is accumulate values as they flow through the observable similar to array reduce. If we wanna keep a running total of all the values that were emitted in this observable, we can use the scan operator and then add the current value to the accumulated value. Now each emitted value gets added on top of the previous one. An important thing to keep in mind here is that the order of operation matters. For example, if we move the scan operator before the map operator, we're going to Different results because the underlying math is now different. So that's how you transform values. But another useful operator is filter which prevents certain items from being emitted in the stream. For example, if we only want values that are greater than 10, we can use the filter operator and that will only emit values that meet this condition. And now we only see values that are greater than 10 printed in the UI. Another thing we can do with operators is tell the observable to complete. For example, if we pipe in take 3, it will only emit 3 values from this observable then complete it. The next thing I wanna show you is an operator called tap, which allows you to trigger side effects from inside the observable pipe. In all the examples so Far, I've been printing values to the screen by using the callback in the subscribe method, but that only gives us access to the value at the end of the pipe. Most simple use case that you'll find is just console logging at different points within the observable pipe. The pipe modifies things from top to bottom. So if we add a tap to the very beginning, it's going to print the initial value. And if we map it to something else and add another tap after that, it's going to print a different value. And you can use tap to trigger more complex side effects. For example, you might want to save a value from the observable to a back end database. If you're using something like Firebase, bass, you'll probably wanna use an async function. So basically, it just gives you a context to tap into the observable and do something. Another term you might hear with RxJS is backpressure. And, basically, that means you have an observable that's emitting way more values than you actually need. We can simulate this in the code by listening to the mouse move event on the DOM. Moving the mouse across the screen will cause the observable to emit multiple events every second. RXJS has several operators that can help us with this situation. The first strategy we'll look at is to debounce the events. A debounce will filter out all events until they have stopped happening for a certain period of time, in this case, a 1000 milliseconds. A debounce is really useful for something like a type ahead where you don't wanna make an API call until the user is done typing. You can see here if we mouse around for a little while, nothing happens. Then if we stop, Our event will be emitted after one second. An alternative to a debounce is a throttle. It will emit the first value, but make sure that no additional values can be emitted until a certain time period has passed. We go back to the demo and start moving around, at the very most, we'll get one event emitted per second. These operators are alleviating the back pressure, but they're also filtering out a lot of data. If we want to keep all the data but just not listen to it all at once, we can use a buffer. This will collect all the events into an array and then only emit them when they get to a length of 20. Now we're going to switch gears to another very important operator called switch map. This allows you to start with one observable and then switch to another one, which is very important when we're talking about data. For example, if you're a Firebase user, you probably have an observable of a user logged into your app, and then you might want to switch to another observable of Some information about that user in the database. We can simulate that in our code by creating an observable of an object, and then I'll create a function that returns an observable of Some information based on a user ID. We can't call this function until we have a user ID. So the question becomes, how do we get the user ID out of the observable? The naive way to do this is to nest subscriptions within each other. So first, we subscribe to the user. That'll give us the user ID. Then we create another description inside of that callback for the orders. That code will actually work, but there's a better way to do this. Instead, we'll start with our user observable To compose a new observable called orders, we first add a pipe to the user and then we use the switch map operator, which will give us access to the user ID. And then we just return an observable from it, and you can also return a promise or an array here as well. So if you ever have one value that depends on another value, switch map might be the operator that you're looking for. But there might be other cases where you have multiple observables that you just want to combine into a single stream. We'll look at 2 different functions here called combine latest and merge. And keep in mind these are not technically operators, so we import them directly from RxJS. I'm creating a cold observable of a random number then I'm creating a second observable that just adds a delay to that random number. 1st, we'll use combine latest and it takes an array of observables And it will wait for each observable to emit a value and then emit everything together as an array. Even though the random numbers are going to emit something right away, going to wait for that delay to resolve into a value before it emits anything. Then if any of the observables emit anything after that, it will emit everything again as an array. In other words, it gives you the current state of every observable in this array. So initially, it's blank for one second waiting for that delay and then it emits out the 4 random numbers. In many cases, though, you don't want to wait for that delay. So instead, you can use merge which will just emit each value 1 by 1 as it comes in through the stream. Merge doesn't care about the array position of the observable. It only cares about when it emits it in the context of time. So it emits the first three values and then the delayed value a second later. Another thing you might be wondering is how to catch errors in the context of a stream. You have a lot of flexibility here, but one of the most common strategies is to catch the error and then replace it with some other value. We can do this easily with the catch error operator. It can intercept the error and then emit some other default value out of the stream. And one thing that's really nice about RxJS is you can easily retry Try things by just piping in the retry operator. I'm not going to get into it here, but it's super useful when working with HTTP calls. 1st, I'll push a regular value and then an error to the subject. If we don't catch the error, we'll get this uncaught error in the console. But by using the catch error operator, we can handle it in the background and then provide some useful information to the user in the front end. Now if you're a good plumber, then you shouldn't have pipes that leak. And by that, I'm talking about memory leaks. There are 2 main ways to prevent memory leaks with RxJS. The first way is to unsubscribe from your subscriptions. Take, for example, this interval. This interval is going to run forever. So if we don't close the subscription, it's just going to create a memory leak in the background. One potential way to handle this is to create a variable for the subscription and then call subscription unsubscribe at some other point in the code. This will stop the leak because we can see here the observable only emits 10 values, but there's actually a better way we can do this. We can pipe in the take while operator to the interval itself And that will tell it to emit values only while a certain condition is true. When that condition becomes false, it will stop emitting values, therefore, preventing the memory leak. And we don't need to manually unsubscribe anywhere in our code. That works well in a lot of situations, but sometimes you want some other observable or subject to be the thing that triggers the subscription to stop. For that, we have the take and tell operator and it takes an observable as its argument. And when that observable emits something, it will cancel the subscription on the source. For example, if we wanted to set a timer for 2 2nd on this interval, we could do that by using take and tell with a timer observable. When the timer finishes it will complete the interval and then end the subscription. Gonna go ahead and wrap things up there. We barely just scratched the surface with RXJS, so let me know what you wanna see next in the comments. If this video helped you, please like and subscribe. Thanks for watching and I will talk to you soon.
        