Master RxJS 6 Without Breaking A Sweat | Maurice Beijer | Skillshare
Drawer
Search

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Master RxJS 6 Without Breaking A Sweat

teacher avatar Maurice Beijer, React rocks

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      Course Introduction

      1:36

    • 2.

      Personal Introduction

      1:13

    • 3.

      The Problem

      4:25

    • 4.

      The Solution

      7:31

    • 5.

      Getting the most from this course

      8:20

    • 6.

      Building blocks of RxJS

      8:03

    • 7.

      Observables using of()

      2:07

    • 8.

      Observables using EMPTY, NEVER and throwError()

      2:31

    • 9.

      Creating subscriptions

      5:58

    • 10.

      Observables from DOM event

      2:28

    • 11.

      Timer and interval based observables

      2:16

    • 12.

      Using from() with iterables and promises

      2:34

    • 13.

      Observables from AJAX requests

      2:42

    • 14.

      Creating custom observables

      5:08

    • 15.

      Subjects

      3:38

    • 16.

      Hot versus cold observables

      3:02

    • 17.

      Finding the right operator

      2:46

    • 18.

      The tap operator

      3:56

    • 19.

      The map operator

      2:05

    • 20.

      The filter operator

      2:05

    • 21.

      The take and takeLast operators

      3:09

    • 22.

      The takeWhile operator

      1:42

    • 23.

      The takeUntil operator

      2:09

    • 24.

      The scan and reduce operators

      3:45

    • 25.

      The pairwise operator

      2:38

    • 26.

      The flatMap, mergeMap, concatMap and switchMap operators

      5:21

    • 27.

      The startWith operator

      1:54

    • 28.

      Custom Operators

      3:26

    • 29.

      Testing Operators and Observables

      8:03

    • 30.

      Scenarios Introduction

      1:03

    • 31.

      Preventing Errors from Completing an Observable

      2:33

    • 32.

      Retrying Errors

      3:41

    • 33.

      Incremental Search

      5:57

    • 34.

      Polling Ajax Requests

      1:41

    • 35.

      Drawing on a canvas

      2:34

    • 36.

      Painting

      4:26

    • 37.

      Sharing Subscriptions

      2:26

    • 38.

      Redux like Store

      7:41

    • 39.

      Redux Store Subscriptions

      2:15

    • 40.

      The end

      1:11

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

394

Students

--

Projects

About This Class

Are you struggling to learn the Reactive Extensions Library for JavaScript, RxJS for short? Are you using Angular and seeing Observables returned to you in many places? Perhaps you are using React, Vue or Node. Then again, maybe you only heard about functional and reactive programming and that RxJS makes your asynchronous code easier to write and more concise.

My name is Maurice de Beijer and in this video course I would like to teach you all about using RxJS. During this course you will learn quite a few things. Discover why developing with Observables is so powerful. Learn how to create Observables using the different functions available. Explore different operators to manipulate Observable streams. Examine different scenarios where using Observables makes life easy. At the end of this course you will be able to solve common programming problems using RxJS.

Is this course for you? Never worked with RxJS before? No problem, we will start from the beginning. Already used RxJS a bit but want to learn more? Sweet, start with the scenarios and look at other videos as needed. Do you have a reasonable understanding of JavaScript? Great, you have the prerequisite knowledge. Also have a computer with a modern browser and code editor? Super, you are all set to get started.

What will you learn in your course?

  • After this course you will be able to see where using RxJS makes sense
  • You will be able to solve common programming problems using RxJS

Course requirements or prerequisites:

  • Basic understanding of JavaScript is required
  • A PC with Node, NPM, a browser like Chrome or FireFox and a code editor you like
  • Any previous knowledge of RxJS is not required

Target students:

  • Any JavaScript developer wanting to learn more about reactive programming with RxJS
  • A developer developing Angular applications

Meet Your Teacher

Teacher Profile Image

Maurice Beijer

React rocks

Teacher

Hello, I'm Maurice.

I am a software consultant and trainer, specializing in JavaScript, React, and ASP.NET Core. My work includes a large, global, safety application for the oil and gas industry. This is completely done with React. I have also worked on many other applications.

I am also active in the open source community. You can check out my GitHub account here.

When not building applications myself I teach other developers. The topics vary from JavaScript, TypeScript and React to ASP.NET.

I have received Microsoft’s Yearly Most Valuable Professional Award since 2005. I am also active in the dotNed user group and helps organize its meetings.

See full profile

Level: Intermediate

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Course Introduction: Hi, Maurice here. Welcome to this class on mastering RxJs 6 without breaking a sweat. So what are we going to take a look at in this course? Well, we're going to start with what problem RxJs is trying to solve and then we're going to take a look at RxJs and reactive programming and how that actually tries to solve the problem. We're going to take a look at observables, one of the main building blocks of RxJs. We'll take a look at what they are, different ways of creating them, creating your own custom observables, using subjects which are a way of creating observables and we'll look at the difference between hot and cold observables. Of course, we are going to look into operators. Without operators RxJs wouldn't be all that useful. So we're going to take a look at the goal of operators, how we can visualize them using RxJs Marbles. We're going to take a look at many of the existing operators, not all of them, they are way too many, and we're going to take a look at building custom operators for RxJs. We're going to take a look at error handling and how you could potentially retry failing operations and of course, we're going to take a look at unit testing your observables and your operators. Finally, we're going to take a look at a number of different scenarios where RxJs might make a lot of sense. Things like fetching a request from the web on a periodic basis, handling errors if a request fails, re-trying it, and things like that. See you in the next video. 2. Personal Introduction: Hi Maurice here, and welcome come back to this course on mastering RxJS 6 without breaking a sweat. In this video, we're going to do a short personal introduction, so you know who I am. My name is Maurice de Beijer, and I'm an independent software developer and trainer. I live in the Netherlands, beautiful place, especially in the spring, with lots of beautiful flowers like these tulips. Got some beautiful beaches, this is Scheveningen, and we've got our beautiful windmill, specially in the sunset like this. All of these pictures were taken within 20 kilometers of where I live. I'm also happily married with a wife and a son. I've been an independent software developer and instructor since 1995. In fact, my developer days go back further than that, but that's when I became independent, so quite some time ago. Most of the Microsoft most valuable professional, an MVP, a yearly award I've been given 14 times in a row now. I publish a React Newsletter if you are interested in React developments. See the notes for a link. See you in next video. 3. The Problem: Hi, Maurice here. Welcome back to this course on Master RxJS 6 Without Breaking a Sweat. What's the problem with traditional code? Let's dive into some code, and let's take a look. I've a little sample application here with a couple of buttons. Most of them don't do anything yet, only the Clear Button does. Let's take a look at the codes. We're going to do pretty much the same action with some different items here. We're going to start off with some numbers. We're going to add an event listener to the button. Then we're going to transform the numbers into a different shape. We're going to filter them, and we're going to put the results on screen. First rule, use the map operator on an array to change to shape from just a number to an object with a property x, which contains the number. Then we'll use the filter operator on an array to only return the objects which have an x value which is smaller than seven. That should return a new array. We'll call it data. Now let's put that on the screen so we can see the result. There's the resulting array of objects with a value. Pretty simple. Let's do the same using a time-based interval. Again, we'll add a click handler to the interval button. This time I'm actually going to use fat arrow functions because they're shorter. No technical benefit here, just slightly shorter. We'll start a set interval, and we'll fire at every seconds. Inside, we want to increment a number, so we have to save that outside of this interval function so we can increment it and remember the value. We'll need an array to push the numbers into. First, we will create a new object with the property x containing the number. Again, just like before, we'll increment the number. Of course, we need to filter. Let's filter for number being smaller than seven. Of course, we want to make sure that our interval stops otherwise, it will keep running indefinitely. Let's save the handle and use clear interval to stop it running again. We still need to display the results on screen. Of course, we still need to push the object into the array. Now, if I click on the interval button, we should see the numbers appear one every second. There they are. Objects with the numbers lower than seven. We are achieving the same goal, but the go is quite different. Let's take a look at the Ajax request. I'll go to URL to Ajax API endpoint, and that's going to return a joke, and we'll use length of the joke as the number. We'll start with the fetch request. Fetch in the URL. Then we need to resolve to using a down handler which will give us the response. I'm going to keep things simple. We're just going to assume that everything works and I'm going to call a json function without checking. That should give us the data. The data will have a value, which will have the joke. We'll take the length from the joke. Once we've got the object, we still need to filter and put it on screen if it passes the filter. I'll actually use a value of 75 here because most jokes will be longer than seven characters, probably every single one of them. Let's see if the Ajax request button works. We see a joke 40 characters long and one 73 and another 54. But sometimes, when I click to UI, it doesn't update, because we'll get a joke which is more than 75 characters long. We've seen three different coding styles. We did a functional approach with the array. We did an asynchronous approach with the fetch, and we also did another asynchronous approach using set interval. They're all very different, completely different APIs. Usually, it's a mixture of functional codes and imperative codes. But all of that is tied to events, like we're waiting for our button click and then doing something, and it's all very different APIs. See you in the next video when we'll take a look at how RxJS will simplify this into one API. 4. The Solution: Hi, Maurice here. Welcome back to this course for Master RxJS 6 without breaking a sweat. In this video, we're going to take a look at the code we did in a previous video, but then make it simpler and more concise, using RxJS. Let's dive right into the code. The first thing we need to do is install RxJS, we're going to do a npm-install RxJS. That's RxJS installed. Let's restart the application and start using RxJS. Here we have the application. So the first thing we need to do, is import some code from RxJS. Let's start with the Array. For the Array, we've got a static set of data, so we need to import the from function from RCS. That will let us turn a static array of data into an observable. Let's go and type goat in the event handler. I start to work on the coal from false in the array of numbers, which turns it didn't tune observable and then we get the value losing to subscribe function. Let's subscribe and add the handler to it, which will be called for our data. In here we're just going to display the data, so what's going to happen? This is going to turn each individual number into an event. The text content on the result will be updated ten times and we'll see the last item. There we see that 10 being displayed. We want to be able to manipulate the data between creating your observable into subscription. We can do that by calling the pipe function and pausing RxJS operators into that pipe. We'll import some operators. The first operator will import is to map because we want to change the number into an object with an X. We call map inside of the pipe function,and we take the number that comes in and we turn it into an object with an X property, just like we had before. We see we get an object with the lost value of 10. We still need to turn this into an array with all the value and filter. We'll use the filter and the scan operator to do that. We'll import them. Go back to the pipe after the mapping in the pipe will do to filter. Just like before we filter on the x property being smaller than seven. Then we'll use a scan operator to turn individual elements into a collection of elements, will turn are the separate events into an array of events. The scanned gets two parameter, the previous value in the current value being emitted. So the previous will be an array, so we'll just return a new array by concatenating the current value to it. We'll tell it to start with an empty array. There we have it. An array with numbers from zero up till six, everything smaller than seven. Let's do the same with the interval, will import a new function from RxJS to start an interval which is gold interval, easy. We'll replace the body of the interval button click handler to use interval function from RxJS. Again will trigger an event every second. Let's copy all the code from below, the whole pipe with the operator. There we see the interval firing, printing all the numbers from zero to six in the objects. Now in this case, the interval doesn't actually stop yet. It keeps on firing, but it won't emit any more events. We'll fix that in another video. Let's go and do the same width, the AJAX request. We'll import the AJAX objects from RxJS/ AJAX. We'll use that to get the Json from the Chuck Norris API. Using ajax.getJSON, we get an observable with the AJAX request or a response, I should say, that will come into the existing code. Again, I'll copy the code we had before. Now the result is slightly different, so I do have to do another map function, basically mapped linked of two joke to devalue. In this case, just having the length is good enough because I'm already mapping it to an object on the line below. Let's change the filter value from 70-75 because there are very few, if any jokes which are fewer than seven characters. There we see the AJAX request working. All three events are done with pretty much the same code. Just to AJAX request is slightly different because of the data and the filter length. But other than that it's identical. It's all a matter of really, really simple functions. But we can actually take this a step further, because the event handler on the buttons can be observables as well. Let's change the tuning firm event. We can turn DOM events into an observable. We pass in the bottom, and we pass in the events. We're interested in the click event in this case, we've got an observable stream off clicks, we can pipe, that's an using another operator to switch map. We can actually turn that into a different event stream. We're switching from one event stream to another event stream, which map from the original click events to the AJAX events. There are AJAX event is still firing. Let's do the same for the interval and the array of numbers button. The interval is working, lets clear, reboot and we'll see the array works as well. We're just using one API for DOM events, for fetching asynchronous data, for working with an interval and working with a static array of data, which I think is really neat. Just learn one API and you're good to go. So we've seen that ArcGIS creates observables that produce events over time. A click event, fetch events, completed, an interval event, anything like that. Events can fire as often as they want to. You might have an observable with zero events, you might have one with hundreds of events. We've seen operators where we can manipulate those events, strings and change events or filter events or new things with them. You seeing that those operators are very focused, they do one task that do that well. That means that we've really simple functions which are easy to unit test and easy to combine into something more complex. We've seen that we can start with one single string, a click event, and then turn that into a series of other events, which is really nice. See you in the next video. 5. Getting the most from this course : Hi, Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video, we're briefly going to talk about how you can get the most out of this course. There are lots of videos, and one way you could start is just watch them from start to finish. No problem, you can do that if you like. But if you're more interested in specific use cases for RxJS, you might want to start with the scenario section. In there I describe several use cases like an incremental search or drawing application, and you can look at those and decide on what videos you're interested in. Then you might switch to specific operators. Then again, you might already be using RxJS, so you might be interested in specific operators or specific ways to create observables. You can directly go to these videos. Either way, you can get a lot of information from these videos. Now, I'll be writing a lot of codes. Every time you see this guy popup, it's not me, but I use this slide, then I'm going to write a lot of sample code. All of that sample code is up on GitHub. If you want to use it, and I highly recommend to do, go to GitHub and clone it from there. This is the Explore repository. My GitHub username is Mauricedb, and repository is called master-rxjs-6-without-breaking-a-sweat. If you want to clone this, scroll down a bit, click on "Clone or Download". If you're a Git user, just copy the URL here. If you're not, go to Download ZIP and download the code that way. I'm just going to copy the URL. In the console window, I'm going to clone it, git clone and paste in the URL and hit "Enter". This quickly downloads the complete repository into a new folder. Now, if I cd into that folder, if you now run npm install, it will install all required npm packages, so you can actually run all the code. Now, there's a nasty security warning there. Don't worry about that. That's not from RxJS, that's actually the results of a prime number package I'm using, and that has an odds dependency which causes the error. If you're not using that, just using RxJS or Partial which I'm using to compile and bundle all the code, it's going to be just fine, you won't see that same error. There we are. We'll take a look at the code in a moment. Now, if you run into any issues with the course or examples, checking the source code is pretty much a first. Compare your code to my code and maybe you spot a difference. If you need to know more about one of the operators or ways of creating observables, the RxJS documentation is also pretty good. This is the RxJS website, at rxjs.dev. It's pretty nice, and the reference section is pretty good. You can see all the different RxJS operators and ways of creating observables here, or with a nice filter. The reactivex.io website is also pretty neat. It contains more information. If I go here to operators, you can see a lot of information about operators. One thing that's really nice is the decision tree to decide what operator or function to create a new observable you actually want. Not just about RxJS, but about the whole ReactiveX family, but highly recommended. Of course, you can ask questions in the Q&A section and I'll answer them. But maybe not just me. I highly recommend you answer our questions too. It's not because I don't want to answer them, but thinking about an answer is actually a great learning tool. One of the reasons I got into teaching about software development was because I wanted to learn more about it. The best way to make sure you know most things about the technology if you can explain it to others. Now, I highly recommend you practice all the code. Watching videos is neat, but coding it is actually way, way better to learn it, so code things up. I've created a little starter template. If I open up the project using Visual Studio Code, my editor of choice, you can see lots of folders here for all the different projects. It isn't there yet, but I'll add it before this course goes live. There will be a folder called 000-template. That's the boiler plate I use for all of these. It's got a little Start button. It's got most important things about working with partial-js in there. That's a great starting place. If you want to run this, you actually need Node and NPM installed. I've got Node installed. The way I can check is run nodes dash dash version with a single V. Then you can see I'm at Node 8.12, which is actually slightly out of date, but that's fine. That will work just fine. If you need to install Nodes, go to the Node.js Website and here you can download the latest version. I recommend using the LTS version, the Long-Term Support version, that's usually the best one. You see I'm slightly out of date, but that's actually no problem. Now, usually when you install Node, you get NPM for free. There are a few distros where you don't, but normally that's included. You can check by running npm dash dash version, and then you can see that I'm at NPM 6.4.1. Both are needed in order to run things. You also need a browser. All the examples run in a browser. I use Chrome, but another reasonable modern browser like Safari, Firefox, Arch, they're all going to work fine. It's really up to you. You'll need some code editor. I use Visual Studio Code, but it's really up to you. You want to use Sublime, Notepad plus plus, Visual Studio, WebStorm, it really doesn't matter. Visual Studio Code is really great, so it's highly recommended. But all of the others will work as well. Now all the samples are in numbered folders. Basically, the 100 folders are the intro. The 200 series are all about creating observables. The 300 series are all about operators and the 400 series are all about different scenarios. You can run them all in the same way. Basically, fine to write number for whatever you're interested in. Suppose we want to run the incremental search, that's folder 403. What we do is we do an npm run start: 403. That starts a little web server and compiles that example and makes it ready to run in the browser. In the browser, you can open that up on localhost port 1234. We see partial bundle the application and start a server at localhost port 1234. Let's copy that. Once it's done, we can go to the browser, open up a new tab, go to localhost port 1234, and we see the application. Now this will actually search GitHub users. If I search for Maurice, I see my own user as the second one, all the examples work in a similar way. In some cases, you'll need to open the dev tools because console.log statements are used to output things in the dev tools, and most cases, you'll see a lot of output in this normal screen as well. If you start editing things, partial is really nice. If you make a small change, partial will automatically recompile the codes and update the browser, so no need to press "F5" in the browser most of the time. It usually just works. Occasionally, if you ever had a syntax error, partial might not be able to refresh the browser, it might be broken. But usually, that will work automatically. See you in the next video. 6. Building blocks of RxJS: Hi, Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video we're going to talk about major building blocks of RxJS. Here we've got a nice diagram with the main building blocks. I actually took this from the ReactiveX website, which is pretty neat to take a look at. Here's to ReactiveX website and if you go to Docs Observables, you'll find that same diagram there. This website is cool because it has a lot of documentation, will visit it again later. But it will also show us all the different languages. There are quite a few here. But if you click on Others, you'll see longer list. Knowing RxJS will translate well to other languages, which is always nice with technology. But more about this diagram. To top you see a timeline an Observable timeline. The little shapes on top of it are events being emitted over time. The little line at the end is the observable being closed. After that, no more events are going to be emitted. The flip here is an operator. Operators get a chance to operate on all events being emitted. In this case, it just flips them around. An observable is a collection or zero or more events over time. Observables can be opened or closed. As long as they're open, they can emit events, but wonder close they can't do that anymore, and they can be close because of the successful closure or an error. This is the RxJS Marbles sites, which is a really nice sites to see how things work. Actually clone it and I'm going to use it to demo some of the examples. Here we have timeline. Here is an empty timeline. No events being emitted. But at a little vertical bar at the right you can see where the time stops and the observable is close. Here's an interval. Probably the quintessential observable, it emits an event every so often, in this case, every 20 milliseconds. Now, the little line at the front suggests it's closest end, but it doesn't, it just keeps going forever. Observables are just a long stretch of events over time. Observables wouldn't be much good if no one is observing them. We've got an observer and the observed subscribes to one observable and is notified of all events emitted. It can do whatever we want to do with it. In the example I'm going to do, I'm just going to display them. We also have operators. Operators are the thing that really makes RxJS interesting. Operators can do all things. Like here I've got the filter operator that filters out the old values. It doesn't borrow zero, two or four because they're even, it just passes on one and three to the targets observable. In this case, we see that the source and the target observable, the one at the top and the bottom have the same life span. Another operator is take three. It just takes the first three events being emitted from the source observable emits those on the target observable and when it's found three events it closes. The source emits 0, 1, 2, 3 and 4, but on the target we only have 0, 1, 2 and the observable is closed. Operators are typically really simple, pure functions, which makes them easy to write. The real power comes from combining them. Combine lots of different operators to achieve the desired effect. When we subscribe to an observable, we get a subscription object. Sometimes you don't need it but subscription can be useful if you want to unsubscribe to an observable. Unsubscribing will stop the observable from emitting any more events. Let's dive into some codes. Now, you might be wondering why I'm not using that Rx marbles, which I just showed to demonstrate the code. The reason is because it's based on RxJS 5, and you can see the codes. Here's the RxJS 6 syntax, quite a bit different. We are focusing on RxJS 6. We're not going to use Rx marbles to demonstrate. I'm just going to use a custom project like this. The first thing we need to do is import from RxJS. The thing we need to import in this case is the interval because I'm going to use the quintessential observable, emitting an event every second. We're going to define the stream variable to hold all the observable events and a convention. The naming convention often used is to postfix variables holding observable streams with a dollar. You don't have to do so, but it show for what it is. Stream dollar is our observable stream emitting one event every second. We need an observer to listen to that stream. The observer I'm going to use is an object which has a next function and that next function is going to be code with every event being emitted. In this case, it's a normal function and E is the event being emitted. I'm just going to display it in a little div elements. Using the stream I can subscribe possibly the observer and this will return me a subscription object, which I can use to unsubscribe later if I wanted to. If I hit the start button, it will activate the interval observable and there we see second ticking by. Let's add an operator. Again, we use an import, but this time we use an import from RxJS operators. The operators are imported from a slightly different part of the package. We'll import the filter and the take operator to achieve the same effect I had in the Rx marble diagram. The big difference with RxJS 6 is used pipe operator for filters with RxJS 5 that didn't exist yet. I use pipe and specify the first operator there, the filter. With RxJs 6 you use the pipe function to pass in operators. In this case, I'm going to pass in the filter operator and filter out all the even values. Now, if I hit start, I'll see 0, 2, 4, etc. I can combine operators specified to take operator that I only want to take the first three values. Now, if I hit start, I'm going see 0, 2, 4. But then the operator then kicks in and it's closest to stream and no more values are going to be emitted. Pretty nice way. Now the order of operators is important. They operate on the stream in the order they're defined. If I put a take first, it's going to take on the original stream emitting 0, 1, 2, 3, 4 and etc. It's only going to take three values from their 0, 1, 2. The one is dropped by the even filter and we only see zero and two. Now, let's disable to take for a moment so it keeps on emitting values, and we can see the effect of unsubscribing. We'll use the subscription and after five seconds, I'll call the unsubscribe function needs to stop the subscription. Now, when I press start we'll see 0, 2 and 4 and more events because we've unsubscribed. The major building blocks of RxJS, observables, observers, subscriptions, operators, and the pipe function to pass operators into. See you in the next video. 7. Observables using of(): Hi, Maurice here. Welcome back to this course on Mastering RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at the of function to create new observables with a fixed set of values. Of() is really simple, it takes a number of values, zero or more, and it will create an observable and immediately emit all those value on the observable. Then it will automatically close the observable. Let's take a look at the code. RxJS marbles diagram for an observable just emitting one. You can see it emits the value one and it immediately closes. In order to do this, we need to import off from RXJS, so that will create a new observable. We'll define a new string variable and assign it to the result of grading of with the values 1, 2, 4. Next I'm going to subscribe to it, I'm just going to use a simple function. I'll explain more about the different ways of subscribing in another video. Let's just set the text contents of the result elements. If I click Start, we see the value four, in fact all values were emitted, but that's hard to see because they're emitted immediately, so we only see the last. Now let's add the console.log so we can see that all values were emitted. There they are they show up in the log, and if I click again, they're printed the second time. Now let's print just before we subscribe and just after we subscribe. We can see that's everything you see even synchronous. We're writing asynchronous like code, but it's really executing synchronously in this time. See we get before subscribe and after subscribe and in-between we get to values being emitted. The of() is a really simple function to create observables. It synchronous, it just emits all values and it closes. See you in the next video, when we'll take a look at some more ways of creating observables. 8. Observables using EMPTY, NEVER and throwError(): Hi. Maurice here. Welcome back to this course on Master RxJs 6 Without Breaking A Sweat. In this video, we're briefly going to take a look at three special way of creating observables. You're not going to use this in production code a lot. They're mainly used for testing and some other special cases. The first is the Empty rational function. It creates an observable, which is empty. It never emits anything, and it closes immediately. If you create an observable using the of function without any parameter, it's actually the same as using empty. If we look at the ReactiveX website, we can see empty. It just creates an observable. We can see the empty horizontal line with the little vertical line at the right. It closes immediately, nothing ever happens there. The next to take a look at is Never. It's even simpler. It opens an observable. It never emits anything, but it doesn't close, it doesn't even do that. In that respect, it's even simpler. It never looks like this. We've seen empty horizontal timeline, but not even the close line at the end. The last way of creating an observable I quickly want to take a look at is throwError. The first two were actually constants. ThrowError is special that it creates an observable string and it emits an error right away. The string error encloses. No events are really emitted on the stream either. It looks like this. We've seen empty timeline, but instead of the little vertical line to indicate that it closes, we see across, that's the indication that it closes with an error, but no other events, nothing. The empty and never are actually constants.They are also functions there to create them, but they're deprecated. Typically, you use the constant to create a new string. The throwError is a function. It takes an error objects, all three just create an empty observable. The empty in the throwError immediately close it. The first successful, the loss error, and then never doesn't do anything. These are useful for testing operators and other things, and in some cases, for combining strings. See you in the next video when I'm going to use these operators to show you how to set up subscriptions and see the different events like closing, erroring, and emitting happens. See you there. 9. Creating subscriptions: Welcome back to this course on, Mastering RxJS6 Without Breaking A Sweat. In this video we're going to take a closer look at subscriptions. Using the subscribe function, we set up a subscription, but it's actually an overloaded function and we'll take a look at different ways we can pass parameters to it. It's also important to realize that subscribing usually activates an observable. Most observables don't do anything until you call subscribe, and as we've seen before they return a subscription object. The subscription issues to unsubscribe when we're no longer interested in the subscription. Besides using subscribe there is another way to get all values from an observable. You can use the forEach function. It will basically subscribe under the hood and loop over all items, but let's take a look at the code. Here we've got a few different observable streams. The data stream with the numbers 1-4, an empty stream, a never stream and an error stream. With the data stream, all values are omitted just like before, and we only see the last one. But if we use an empty string nothing is submitted at all, we don't see anything. Let's update to subscription a bit. It turns out this variant of the subscription takes a number of different callbacks. The first one is for when a value is submitted. The second callback function is for when an error is detected. Remember the error also closes the string. Let's print the fact that an error occurred, and the third callback is for when the observable string closes. Will not pass any data, but we can print the fact that the observable has completed, and now if we use to empty observable, we can see that we get completed. If we use data, the values are emitted, but we never see those anymore, it's completed. But let's add a console.log so we can actually see the values being emitted. Now we see the values 1-4 being emitted in the console on the right. Complete only shows up in the UI. If we use the empty observable, we only get completed, and with the never observable, nothing at all happens. It's not completed. It never emits. But with the error observable, we can see that the error message is printed. Something bad just happens. Now in order to show that an observable usually does nothing, if there's no subscription, I'll import the tap operator. The tap operator is useful for debugging. You can pipe all events through tap and do something like in this case, just print them to the console.log. Is meant for side effects, not for the normal operators or sets filter or map or something like that. I'm just going to print out tap with the actual value, and if I hit start, we subscribe and we see tap 1 and then the actual value one being emitted, and the same for the other values in the stream completed, but let's comment out to subscription. Now if I click Start we still creates the data observable. We still call the tap operator except it's never executed. It's only executed with a subscription, but this is one way of creating a subscription, but there's another one. We can also use the forEach operator, to print out all values. Deposit goal backwards is called for each value emitted and it returns a promise, and in this case I'm only going to handles a success case. When the promise resolves, the observable is complete, and there we see exactly the same behavior except this time everything is printed to the console. Besides using the subscribe function with three functions as parameters. We can also pass in an observer object, goal subscribe with the observer. If I click Start we still see the tap outputs, so the subscription was activated. Not only observe for object, we can add three functions, next which is called every time value was emitted error, which is called whenever an error occurs and completes, which is called when the observable completes and it's done. There we have it still the same behavior. It doesn't matter which of the two subscribe method should prefer, but in most cases, you should always provide callbacks for both values being emitted, errors occurring and quite often for completed as well, but make sure to always include the error callback. Errors can happen and you need to be aware of those. Let's just import the interval creation function. To create a time-based observable will emit one events every second. The no after five seconds, we call the unsubscribe functional new subscription to unsubscribe from the interval. There we see the second it pause by, but after four it stops. Note that we don't get a complete callback, we're unsubscribing. It wasn't the event stream completing, no error, no completion. If we do the same with the take operator, we just take the first three events. Now things are a little different, but will piped into interval through take operator, taking the first three events and we see 0, 1, 2 and then it actually completes. Now it's the observable completing before we unsubscribe, so we do get the complete callback. Using subscribe is the preferred way to get all the values preferred at overusing forEach gives you more control, more flexibility, uses three different functions there. The next, the error, and the complete as well, if you need to which checks signals when the stream is closed in a successful way. See you in the next video. 10. Observables from DOM event: Hi, I'm Reece here. Welcome back to this course on mastering RxJS 6 Without Breaking A Sweat. So in this video, we're going to take a brief look at the forum event way of creating an observable. Using forum events, you can create an observable from any DOM event or any related standard event like to Node.js. EventEmitter, there's also former vent pattern rational function for other generic events which are not supported yet. Let's take a look at the code. The first thing we need to do is import from event and ignore the lines of code below, there are just about scaling with a high DPI screen I've got. So using fromEvent, I can specify which domain elements, in this case to start button, which event I'm interested in, the click event, and then I can subscribe to it. So in this case I'm just going to shut the result element to the string debts, "I was clicked". There it is, "I was clicked". So using form event, you don't have to select a single domain element at a time, you can select a whole collection. Using query selector all I've selected all the buttons and using that selector I can just create one observable for all of them. I'll basically sets the results elements to the text of the button so we can see it's switch between start and stop. The blue area on the screen was canvas. So let's play around with the canvas a bit. Again, I'll use form events, this case I'll subscribe to the canvas and I'm going to subscribe to the mouse move events. I basically going to draw on the canvas how my mouse moves. That's why I needed the scaling goat below. So I set a subscription, I get the event arc. From the event arc I can get x and the y offsets on the elements. Then using the canvas context, I can fill a small rectangle from two-by-two pixels were the mouse is. But now if I move the mouse over to canvas, you can see dots being drawn. If I move slowly, they're close together, but if I move too much faster, you see that there are actually some gaps because not every pixel is an event. The fromEvent makes it really easy to shut up event handlers and create observables based on those events, at least for most events. Occasionally, you'll need to use two the fromEvent pattern. So see you in next video. 11. Timer and interval based observables: Hi. Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video, we're going to take a brief look at time-based observables, the timer and the interval. The timer is a very simple creational function. It creates an observable that waits for the specific amount of time and then emits, and possibly emits multiple times depending on the second parameter. The interval just starts emitting and keeps on emitting, real simple. We've already seen that several times. Let's take a look at the code. I'm only going to use timer here because we've already used the interval several time. We import timer from RxJS, and then using timer, we specify the amount of time to wait. One second here. After one second, we update the result elements with the events. If I click on "Start", we see after one second, zero bare and nothing else. With the first delay parameter, we just get the single events. If we add the second parameter, it will actually determine the interval for each event after the initial delay. Now, it waited five seconds and then fire an event every second. A nice thing with the timer is that we don't just have to specify the number of milliseconds to wait, but we can also specify dates, objects with the exact time when it should start. Let's create the start time with the current date time and add five seconds to it, and then tell it to start at that specific moment. Again, if I click "Start", it waits five seconds and then starts emitting again. But now because that was the exact start-time, we determine. The timer is really useful, it waits and then, either emits once or depending on the second parameter, starts emitting after every interval and interval starts emitting right away as we've seen before. Both really good for scheduling recurring work. See you in the next video. 12. Using from() with iterables and promises: Hi, Maurice here. Welcome back to this course on Master RrxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at the from() function to create new observables. From() is very versatile, it will basically take anything which is either a subscription or a promise, or something which you can loop over like an array or an iterable and create a new observable based on that. Very similar to the of() when it comes to [inaudible] and set of values except with of () need to be known values. Here it's just an array. If you're using an array or an iterable, it will submit all values synchronously. Of course with a promise, it can't do that. Let's take a look. First we need to import from() from RXDS, and then we'll use from() with it, an array of numbers 1, 2, 3 and we'll just print those to the console when we subscribe. When I click on the Start button, we see the numbers 1, 2 and 3 appear in the console window. Nice and simple. We can work with anything we can loop over. I'm using a query selector all to select all liElements above. Let's loop overdose using the from() to create an observable. An observable of DOM elements. We subscribe and in the subscription I'm going to set the text content of the liElements to using from(). When I hit the start button, the five liElements are updated. We can also use from() with promises, which can be really convenient if you've got some promise based API like fetch or something else. In this case, I'm just going to create a promise and after two seconds resolve it with the value 42. So using from(), I turn the promise into an observable and I subscribe to it. When the promise resolves, the subscription will be called and we'll set the results elements to the value being resolved, 42 in this case. The lis are all updated again and we see the value 42 appear. In all these cases, the observable closes as soon as it knows it's done either with a fixed number of values or when the promise resolves. Using from() is very simple and useful for collections or when using promises. When using collections it synchronously emits all values, and with a promise, it emits when the promise resolves, and in all cases, it's closed right afterwards. See you in the next video. 13. Observables from AJAX requests: Hi, Maurice here. Welcome back to this course on mastering RxJS 6 Without Breaking A Sweat. In this video we're going to take a look at doing Ajax requests. If we want to do Ajax request, we have to import Ajax from rxjs/ajax. Not from rxjs itself but the sub package called Ajax. An Ajax thing we get back is both an object and a function. You can use it as a function to make your request, but there are a number of utility functions from there to make life for most request easier. Usually I just do with ajax.getJSON or an ajax.put or an ajax.post. It's all based around to XMLHttpRequest object. It works in older browsers. Let's do a simple fetch request. First, we'll import Ajax from rxjs/ajax. First I'll use ajax as a function. We have to specify an object as a parameter, and that object can have a number of different settings. If you go to the RxJS documentation, you search for Ajax you'll see Ajax request. Here you can see the list of parameters you can specify. In this case, I'm going to keep things simple. I'm just going to specify the URL. But you can see you've got quite a bit of control. I've got the URL here to an online API which returns Chuck Norris jokes. When the Ajax call is done, it returns an observable and that will emit once ajax request is finished. In this case, the event being passed is the XMLHttpRequest. It has a response object, and underneath the response is to actual response, in this case, there is a value which has a joke. There's a Chuck Norris joke and another. This isn't hard, but in most cases you'll need to specify a bit more. If I know I'm just going to request some JSON data, I'll use the getJSON utility function, just pass it to URL and optionally some headers, go subscribe on it and it will return you to actual JSON payload when the response completes. Though again, I'll get to value.joke from the payload and display that. There we see another joke. Doing AJAX requests using RxJS is really simple. It's all based around to XMLHttpRequest object so it will work with old browsers, and because it returns an observable, you can just treat it as any other observable. See you in the next video. 14. Creating custom observables: Hi Maurice here. Welcome back to this course on master RxJS 6 without breaking a sweat. In this video, we're going take a look at creating customer observables. The first rule of custom observables is don't create them. If you want to create a new observable, see if you can start with an existing one, that's always the best option. Here on the ReactiveX website, if you go to operators and you scroll down a bit, you'll see this option about a decision tree to use operators. Well, it also has this decision tree on using functions to create new observables, and we're going to create a little clock, every second we want to emit to the current time. That's like an interval. We wanted interval except we don't want the numbers from the interval, we want the current time. That's like using an interval width map operator combined mapping to current number, to the current time. But if you can't find any existing creational function which will work through observable.create will let you create new observable. You'll get the subscriber object, it has a next complete and an error function which you can call to emit value. Let's take a look at the code. Let's do the simple thing first and let's start with an interval. I'm first going to create a new function, which will create a new observable for me. Because I wanted time-based, I'm going call it time and passing the number of milliseconds between emitting the current time. Because it's really like interval, I'm going to start with the interval and I'm going to map it to the current time. If important interval and map, and then I create a new interval specifying the number of milliseconds then I'll use the pipe function to run a Trudeau map filter, ignored original number, and worked on a new date to local time string. I can use this time creational function just like any other, just call it with the number of milliseconds, it returns an observable, so we subscribe to it, and whenever it emits an events, we update our results elements. There we see our little clock ticking. Nice and simple and issued to really be the preferred approach. But let's take a look at a different approach, if there's no standard observable, you can really use them. In that case, we're going to import the observable from rxjs and use observable.creates to create a completely blank new observable. We're paused an object to subscriber which will have to next, error, and complete function. These guys are only going to use next to emit values. Because we really no end to time, and we're not going to assume grows and the error. Just to show that we can emit values, I'm emitting the string hello, and it shows up. We want to emit time-based so let's create a set interval, and every so often milliseconds emits the current time. There we see our customers time observable emitting time values. Great. Now we're not quite done yet, because we're starting a set interval and it will keep on running forever. Let's add a console.log in the interval so we can actually see when it runs. Let's capture the subscription when we subscribe, so we can unsubscribe after five seconds. If I hit the start button now, the o'clock will start running, but the element will stop updating after five seconds because we've canceled our subscription, but the console output still keeps on coming. We need to make sure to stop that interval. The way you do any cleanup actions when user unsubscribes from an observable is by returning the clean up function. From the observable.create, the function that creates the observable will return a cleanup function. We'll save to handle from set interval and in clear into full [inaudible] at handle which will stop it. Now when I click "Start", we see time elapsing, but after five seconds when we unsubscribe both the UI and the console stop updating, because we've stopped the interval. Creating customer observables is really easy, although you should avoid it. If you don't have to, if you can use one of the standard observables and just use an operator, that's the better approach. You get the subscriber, you can emits value shoes and next you can complete the observable, or it can emit error if you want to. All in all, very easy to use. See you in the next video. 15. Subjects: Hi, Maurice here, welcome back to this course on mastering RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at subjects and a few special subject types. Subjects are another way of creating observables, but they're special because they're both usable as a subscriber, as an observable. You typically use those for some special cases, but one of them is multi-casting too many observables. You can subscribe many times to the same subject. It's a special case class and you shouldn't really use them a lot. If you want to create a new observable, prefer using Observable.create or even better, one of the standards, observable creation functions. There are three special types of subjects. We've got the base class subject, which we can use, but we've also got an AsyncSubject, which only emits when it's completed. We've got a behavior subject, which takes an initial value and whenever you subscribe, it will emit the lost value being emitted, or if nothing is being emitted yet the initial value. We've got the replace object, which will re-emit all previously emitted values. Or if you specify the optional buffer size, it will emit so many events doesn't necessarily need to be all of them. Let's take a look at the code. Let's start by importing subject from rxjs. Our subject is a class, so you just create a new one using the new operator. If you have a subject, you can go subscribe to set up a subscription. In this case I'm just going to print all the values to the console. Next we can emit some values. Emit two restraints rxjs is cool. When we run this, we can see that I've moved up here in the console window, just like you would expect from an observable. Now if I move to subscription down a bit, so after the 'is' we'll first emit rxjs and then 'is' and then subscribe and then emit cool, we only see the events being emitted after we subscribe. We only see cool in the console. Now let's use the behavior subjects instead of the standard subjects this takes an initial value that will say start. When you subscribe, you'll get to last emitted value as well. Even though we subscribed after emitting 'is', you still see is cool being emitted. If I move to subscription to the top, we see the initial start value also being emitted. If I move to subscription right to the end, we only see the very last thing being emitted. Cool. Let's try the replace subjects. First rule, not passing any values and we'll emit all the value first before we subscribe. Still, everything shows up in the console. With the replace subject by default, it will buffer all events being emitted and new subscription will receive all of them. But we can specify the buffer size. In this case, just two, the last two values being emitted. Subjects are a really useful if you need to multi-cast observables. Or you've gone to wrap your own coat inside of an Observable.create. But they are an [inaudible] smell so don't use them too much. Most people think you should never use them at all. See you in the next video. 16. Hot versus cold observables: Hi, Maurice here. Welcome back to this course on Mastering RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at hot versus cold observables. Most observables are going to be cold. The cold observable only starts emitting data when there is a subscription. If there is no subscription, nothing is emitted. Usually each subscription will get its own source of events. If you have two subscribers to one observable, they'll get their unique set of events. Most observables in RxJS 6 are cold, they don't do anything until you actually subscribe to them, which is perfectly fine. On the other side, there are also hot observables. Hot observables start emitting values even if there are no subscriptions, they don't care. They just start bumping out data. Usually if that happens, and you have multiple subscriptions, they share the same data stream. Different ways you can create hot subscriptions, but typically it's done using a subject, although not necessarily, it really depends on where the source of the data is created. Let's take a look at this behavior in code. Here I've got two button handlers. First I create a cold observable, and then in the click event, I subscribe to it. Below I create the hot observable, and again, in the click event, I subscribe to it. They're both created when the page loads and they're both only subscribed when their respective button is clicked. Let's refresh the page to make sure we start with a clean slide. Wait a bit, and then click on Start Cold. You see we get values being emitted, but it actually started with the value 0. Let's refresh the page again and try with hot. You see that after a brief pause, we started with the value 46. We didn't start at 0, we stepped into the middle of a stream of numbers and started receiving them. What does the code actually look like? For a cold observable, you see the observable is created using observable.create. Inside we start an interval and we start emitting values. For the hot observable, we create a subject and immediately start emitting values regardless of whether there are any subscriptions. We also don't stop sending values if someone unsubscribes. Most observables are cold and that's perfectly fine. They don't need to do anything until you're actually requesting data. Some observables are hot, always emit values. Typical examples of an hot observable would be something like a stock trader. If you're listening or not, stocks are being traded, purchase and sell actions are being emitted. If multiple people are listening, they can listen to the same stream. With a cold observable, if no one would be paying attention, no sales would be made. See you in the next video. 17. Finding the right operator: Hi MORRIS here. Welcome back to this course on mastering arcs ES6 without breaking a sweat. In this video we're briefly going to take a look at finding operators to use, because there are many and finding the right ones can be little hard. We've got the RxJS websites and there's a lot of documentation about operators there. Let's actually go there for a moment. Here we have to RxJS websites and reference to all the functions there. There's a lot of them. If I scroll down to operators, there's quite a list. Now if you know which operators who are interested in, for instance, stop. You can just find it here and go to it. But if you don't really know which operator to use, you've got a problem and which operator do I need to solve. This site is hard to use. In that case, to reactiveX website is a lot easier. They actually have this decision charts on finding the right operator, not all of the operators are there, but a lot are. It's divided up in such a way that you can actually go through. This is what I want to solve. What operator would I use? If we open this, you can see it's divided up into different sections, grading a new observable, which is not about operators, but lots of other things. Suppose I want to emit items from an observable after transforming them. Well, one at a time, use the map function. An observable at the time, use concat map. You can see there is a nice decision. I only want to re-emit certain items, which happens quite often. You can use to filter or fast or take or lost, or skip some, etc. It's a lot easier to find operators this way so I use this quite often. Just keep in mind that some operators are named differently. If we look for errors, like I've got an observable and I want to recover gracefully from a notification we can use to catch operator. We should catch error. lf I scroll down a bit, I'll see implementations for different languages so we'll see catchError for RxJS. But if we go and search for RxJS catch, we see it's actually named catchError. The reason is because catch is a reserved keyword and it's a standalone function so it can't be named after a reserved keyword. See you in the next video when we'll start using different operators. 18. The tap operator: Hi, Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video we're going to take a look at the Tap Operator. The tap operator is intended for side-effects. Use it for debugging, which I often do, or some other side effects, it takes a subscription just like the subscribe function, so either three functions for next error incomplete, or an object with a three functions. Unlike subscribe, it doesn't actually activate the observable. Here on the RxJS website you can see we've got documentation for top with the three parameters it takes. Non ReactiveX website, we can find it as well, except it's called "Do here." The reason is death in most Rx implementations, reactive X sweet with all our different languages uses to do operator. RxJS varies from that with the number of operators because of restrictions. With most other ReactiveX implementations, the operators are functions only observable objects. That used to be true for RxJS as well. In that case, Do and catch for instance was fine but there are reserved keywords, well, you can use them as a function on an object. You can't use them as standalone keywords. With RxJS 6, we go capable operators and they had to be standalone functions so they didn't rename some of them, and Do was renamed to tap and catch was renamed to catch error. That's why there are slight differences in naming. Older ReactiveX website is great because the documentation is much more complete and there are nice diagrams about how it works. Let's take a look at some codes, we've got a simple timer here, it went for two seconds and then emits but also before we start the timer, we disable the button and when it fires, we re-enable it. The button is disabled and re-enabled when the timer fires. In fact, that should have been done when it's complete, but it told me fires once, not much difference. Let's import tap and let's use the pipe function to tap operator into the observable. Like subscribe, who can use a simple function, falls into the function and prints the current item being emitted to the console. Open up the Console window, Start, and after two seconds we see the item being emitted. Quite often actually shorten this I just called Tap and Push in reference to counsel will block, which will actually output exactly the same thing. Just slightly shorter syntax. There we see it. Now in this case I've actually got the side effects in the subscribe function to re-enable the button. That's where the tap operator comes in. I'll use to complete a go back in the tap operator and re-enable the button in there. Now my subscription is only interested in the value and side effects like re-enable the button or delegated to tap operator. It works within this case, it actually looks a bit funky because I'm passing in no twice for the first two parameters so in this case, passing in an object with the complete callback makes more sense. Let's change the syntax, it's still behaves exactly the same way when I click "Start," disabled, and afterward emits it's enabled. Tap is a really useful operator, I use it for debugging, but it's useful for other side effects like disabling, enabling buttons as well. See you in the next video. 19. The map operator: Hi, Maurice here. We'll come back to this course, to mastering RxJS 6 without breaking a sweat. In this video, we're going to take a look at the map operator. The Map operator is really useful. It takes an input's objects and transforms it into some output objects. Basically, input goes to output of some different shape. In some cases, all you want to do is extract a single value from the input object. In that case, the block operator is another alternative. But in this video, I'm just going to use ''Transform''. Let's take a look at the code. Here I've got a canvas example we used a while back, when we looked at getting observable streams from DOM events. It works just fine. But didn't subscribe, I'm actually using the original mouse events, everything that is there, so we're getting far more data than we actually need. I'm also using these global context objects. Let's import the Map operator to fix that. We'll pipe the events through to map operator and we'll extract the values we need. In this case, the offsetX and offsetY. The subscribe no longer receives to complete event arcs, it just receives to position now. Let's update the code and subscribe to reflect that, use the position X in the position Y. Our pencil still works and we can draw on it. Great. We're still using that context objects from the outer scope. Let's capture that as well in the map, because we are going to retrieve that from the eventact.targets.getcontext 2D. Now we're no longer dependent on that context variable from the outer scope. We're just posting everything that subscriber actually needs. Great. The Map operator is really popular. It's used a lot. It's really great to transforming an object from one shape to another shape, or for that matter, it doesn't need to be an object, anything will do. See you in the next video. 20. The filter operator: Hi. Maurice here. Welcome back to this course on Master in RxJS 6 without breaking a sweat. In this video, we're going take a look at a very popular operator, the Filter. As the name suggests the filter will just select items to parcel. It gets every item being emitted by the source observable and only amidst things passing the filter on the target observable. Important to note is that the filter does not affect closure of observable. Unlike some other related filtering operators like take and first, which will do that. Here, we can see the Rx marble diagram for filter. We see the input observable stream with the values 2, 30, 22, 5, etc. We see only the values larger than 10 being emitted on the output observable. Let's take a look at some code. I've got a little timer here and it's basically going to emit a new number every half a second. I've got to tap operator to print it to the Console and I'm going to display them in the UI that we see the values 1, 2, 3, etc, appearing. Let's filter this to only using prime numbers. First, we import the filter operator. Forward, we go to the function to filter primes. Next in the pipe function, we add the filter and for every value being emitted, we test its primness. I'm doing this after using the tap operator. But when I click "Start", we'll see all the numbers being emitted in the Console, but only the prime numbers in the UI itself. Not order is important if I move filter first and tap, second operator, then I'm first going to filter and then going to print to the Console. Now, I'm only going to see prime numbers in the Console. Filters and other very poplar operator for quite a few filter like operator for very distinct use cases. See you in the next video. 21. The take and takeLast operators: Hi, Maurice here. Welcome back to this course on mastering RxJS6 without breaking a sweat. In this video we're going to take a look at to take operator and the related take lost. The take operator will let you take the first x number of items being emitted to an observable, take last is two opposite. It will give you the last x number of values being emitted its own observable. So take is different from filter, filter does not change when the observable was closed. Take will close the observable as soon as the number of values require to our front. Here we see the rx marbles diagram for take. So input observable emits one, two, three, and four. We only take the first two. So we are left with one and two. Take lost with one. Again, input emits one, two, three, and four. Take lost only emits four, but note it only emits when the input observable is closed. Only then does it know what really is last item being emitted? Let's take a look at some code. Here, I've got a button with an interval which emits a value every half a second. We're going to print to the console log. We're going to display it in the UI and UI we're also going to display the fact that the observable was completed. Now the observable just keeps on emitting values because we never stopped. Let's take the first five values. We'll import to take operator, and then I'll pipe the observable true to take operator. There will post five in to take the first five items. There we see the items appearing and the observable being complete. Let's change this to take lost. We'll take the last five elements. When I click Start, you see numbers being emitted by the tap operator, which is before to take lost, but nothing appears in the UI. That's because to input observable never closes. So take lost doesn't know when to emit values. Let's use that operator to take the first 10 values being emitted, which closest the observable afterwards. Then we'll use take last to take the last five values of those. We can see in the console log that 10 values were emitted, but in the UI we only saw completed. That's because take last emits upon completion. But when we move to tap operator as the last operator, we can actually see what was being emitted in the console. Click Start again. It's emitting values. Take losses, capturing them, and now it emits the lost five values. So take and take lost are pretty useful to capture a subset of the elements being emitted. The first or the last. If you just want to very first, or very lost results over first and the last operator, which are useful. They also take a predicates and the default value in case nothing is being emitted by the time the observable closes. Capabilities that take and take lost don't have. So see you in the next video. 22. The takeWhile operator: Hi Marie share. We'll come back to this course on mastering arcs ES6 without breaking a sweat. So in this video, we're going to take a look at another operator to filter data the TakeWhile, operator. The TakeWhile is like the filter operator and the take operator combined. It takes the first number of elements being emitted on observable, but to number of elements being emitted. It takes depends on the predicates. Unlike it take, which takes a fixed number, it will use a predicate just like the filter. Unlike the filter which keeps the observable open and just emits anything that passes, TakeWhile will close your observable as soon as the first item admitted does not pass the filter. Here you can see the arcs marbles diagram for to take while see the filter condition is x being smaller than five and as soon as six is emitted, the output observable is closed, and you can see if I move the six after the four the four has made it, and if I moved to seven earlier, death closest to string. Let's take a look at some code. Again, we've got a little interval which will emit a new number every 500 milliseconds. Let's import to TakeWhile operator and take elements as long as we're below five. If I click Start now we'll see the first five elements being emitted, but as soon as we reach five, you observable is closed. Take wells quite usual models versatile as filter, but still quite useful. Remember that it actually closes the output observable. See you in the next video. 23. The takeUntil operator: Hi, I'm Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video we're going to take a look at TakeUntil Operator. That TakeUntil operator is very much like to TakeWhile operator. It takes values being emitted from one observable stream and emits values until it's told to stop. We don't like TakeWhile, which uses a predicate, TakeUntil actually uses another stream to determine when to stop. Here you can see the orange marbles diagram. You can see TakeUntil takes elements form the first stream until the second stream emits. If I move the first element on the second stream, you can see the resulting observable is actually a change. Let's take a look at the code. Just like before, I've got the start button which listens to a click event and we'll start an interval emitting every 500 milliseconds. In this case, I've also got the stop button and now you using the Forum events function to create an observable whenever we click on it. I'm going to tap operator there just so we can see when we click on it. Note that I'm not subscribing to the stop event. If I click start, we see values being emitted. But if I click stop, we see nothing happening. We don't see the console message cause we're not actually subscribing to that event. Let's use the stop button to stop the interval string. I'll import TakeUntil operator and by the interval stream through TakeUntil and policy in the stop string there. I click on start and the event stream is running, I click on stop and it stops. Note that if I only click on stop, nothing happens because there is no observable features to it yet. We need to start the first stream before the second stream is subscribed to. TakeUntil is quite useful. It combines two streams, one input stream and one other stream to determine when to stop taking events from the input stream. Remember it's closes the output stream as soon as the second stream emits. See you next video. 24. The scan and reduce operators: Hi, Maurice here. Welcome back to this course on Master RxJS 6 without breaking a sweat. In this video, we're going to take a look at two very comparable operators, the scan and the reduce. They're almost the same. The scan operator takes an accumulator function which takes the previous result and the current value being emitted, and obviously it takes an initial value and then it's going to emit every value from the accumulator. Here we can see the scan operator at the Rx marble site. You can see for every value being emitted on the input observable we get a value being emitted on the output observable, the result of repeating the accumulator for every value. The reduce operator takes exactly the same parameters, an accumulator function taking the previous and the current value being emitted, and an optional initial value. The difference though, is that it only emits when the input observable is closed. Here we see the reduced operator on the Rx marble sites, and notice it only emits once at the end when the input closes. Let's take a look at this in code. I've got some sample code, and I start with a range of a few numbers. If I click the start button, we just see the numbers emitted and I see the last number emitted a five in the UI. Let's import scan and reduce, and let's first use to scan the operator. The scan takes a function which has a previous result as the first parameter and the current value being emitted as the second parameter. The very first time the previous value will be the initial value we pass in. If there is no initial value being passed in, then the very first value being emitted will not cause the accumulator to run, it's only at the second. Then the first value is the previous and the second value being emitted is the current. But in general, I always use an initial value, and if I hit the start button now we see the sum of 1-5, which is 15 bearing. Let's do the same with the reduced function, instead of scan we'll use reduce, and if I hit "Start", we see exactly the same output. We can't really tell the difference between scan and reduce right now, so let's take an interval instead of a fixed range of numbers, and the big difference here is of course, that the interval doesn't close because time keeps on taking. With scan operator, we see all the immediate sums of the values being emitted and if we tried the same with the reduce operator, that's not going to happen. If I hit "Start", we see values being emitted in the console but in the UI, we don't actually see your results. That's because to interval stays open, it doesn't complete so reduce never actually emits a value. Let's import the take operator and take the first 10 values from the interval. Now the observable completes and now reduce will, after 10 values being emitted, emit the results of the sum of all numbers being emitted. Scan and reduce, very similar, both take an accumulator function with an optional initial value. The difference is when they emit, scan emits every time, reduce emits upon completion, usually reduces a great operator to use, but it only works if you've got an observable which closest. So see you in the next video. 25. The pairwise operator: Hi, Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video we're going to take a look at the pairwise operator, which can be rather useful in some cases. The pairwise operator basically combines two elements being emitted on the input observable onto the output observable. Every event emitted on the output observable is an array containing two values, the previous and the current value being emitted. There two similar r operator, bufferCount, which is a bit more flexible because you can specify the array size being emitted, it doesn't have to be two, or bufferTime which takes timespan and just collects up all the items being emitted in a timespan and emits them as one array. Here you can see the pairwise operator on the RxMarble's site. You can see that the input observable emits A, B, C, D, E, F. The output observable emits the arrays A,B, B,C, C,D, etc. The very first item does not have a corresponding item being emitted on the output, but all the next one are their values with the previous one. Let's take a look at some code. Here I've got the Canvas sample again we used before. Remember when I move the mouse over to Canvas, we can draw on it, but it draws dots where the mouse is. If I move the mouse fast, we get more separation between the dots if I move it slowed are close together. Using those dots and pair wise, we can actually turn those into a line. Let's first import the pair wise operator. Then after we've mapped our events, we turn it into pairs by piping it to pairwise operator. Now in our Subscribe, we get pairs of positions, not just single positions. Let's use the [inaudible] the structuring syntax to get the from and the to position from the pair. We'll get the context from the first one, doesn't really matter which of the two we use. Now using the context API, begin off, move to line two and stroke. We can actually draw a little line between the two points. Of course, pairwise should be a function call. So now if I move the mouse over to Canvas, we get a nice line instead of a row of separate dots. Pairwise can be very useful for these kind of situations where you want to pair up things. The bufferCount operators are bit more flexible because you can specify the exact buffer size you want. See you in next video. 26. The flatMap, mergeMap, concatMap and switchMap operators: Hi, Maurice here, welcome back to the scores from Master RxJS 6 Without Breaking A Sweat. In this video we're going to take a look at various map operators. They're basically all designed to map one observable into another observable, so we'll look at: flatMap, mergeMap, concatMap and switchMap. First we'll look at flatMap and mergeMap, and we'll lump them together because flatMap is just an alias from mergeMap. They're really exactly the same thing. MergeMap starts emitting events from a nested observable as soon as the outer observable emits. MergeMap will basically emit all values from nested observables regardless of what's happening. If the outer observable emits three times, it starts the nested observable three times and it will just keep emitting events from all those observables, so they are all interleaved together, there is really no discernible order there between them. ConcatMap is little different. ConcatMap also emits events from the nested observable when the outer observable emits, but it waits for the nested observable to be completed before it starts the next one, so there's no interleaving and everything is nicely ordered. It still waits for the nested observable to be completed though, so if it doesn't complete, it won't fire again. Here you see the RxMarbles diagram for concatMap and you'll see if I move to C or to B events on the outer observable that the observables are just queued up. The last map function, we're going to take a look at is switchMap. SwitchMap is somewhat like concatMap in that everything is nicely ordered, but in this case, when the outer observable emits again, it's going to cancel the inner observable. Here you can see the RxMarbles diagram. Notice when I move the events on the outer observable, that events from the inner observable are dropped if I move the B to the left, so it fires earlier, we see that not all the nested events from the first in our observable actually fire. Let's take a look at some code. Here we've got some sample code. The outdoor observable is basically a click observable from the start button, so we're using it from events to create an observable. I pipe that into a scan operator just so we get incrementing values and we can see which click it fires. If I click the "Start button", we'll see the number 1, 2, etc. Let's use the mergeMap and the nested observable in this case is just a range of numbers 1-5 and I use the map operator to turn it into a little string showing you from which click it originated or which event it is in the nested observable. If I click "Start", we see five events being emitted and if I click "Start" a couple of times, we see exactly the same thing emitted again. Let's try with concatMap and we get exactly the same output. At first glance, it looks like they behave exactly the same. Let's quickly try switchMap and again we get the same output. It doesn't seem to be a lot of difference. The reason is that the nested observable is created from a range, so it runs really fast and it's already done by the time we click again. Let's try with an interval, so every seconds we're going to emit an event in the nested observable and will take five events again. If I click on "Start" multiple times, you see that events are interleaved. We get click and events are all interleaved together and there is no real good discernible order there. Let's change from mergeMap to concatMap now, and again if I click "Start" multiple times, we'll see a very different behavior. In this case, we see all the events from Click 1 and then when that's done, we see all the events from Click 2 and then all the events from Click 3, so everything is nicely in order. Now, if I remove that take five, we basically have a nested observable which never completes. If I click, you'll see all the events from Click 1 appear, but if I click a couple more times, we never actually see events, it waits for that nested observable to be completed, which it never is now. Let's take a look at switchMap. If I click "Start", we'll see the events from the first click appear, but if I click "Start" again, that first nested event stream is canceled and a second starts. If I click "Start" multiple times, you see a new event stream starting every time, but the first one is canceled. There are several map operators to combine streams, they're all similar, but slightly different in how they handle nested event streams, so pick the one you need for a specific job, we'll look at what happens with the nested event stream when multiple events happen on the outer event stream. They're all useful, they all have their use cases. See you in the next video. 27. The startWith operator: Hi, Maurice here. Welcome back to this course of Mastering RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at the startWith Operator. StartWith is an operator which lets you add one initial events before all the others are emitted. We'll just insert one value and then keep on emitting all the other events it receives. This is the [inaudible] Marbles diagram for startWith. You can see the originating observable emits two and three, but startWith starts with one, so it emits one, two, and three. Let's take a look at some codes. Basically, you have the same setup as in the last video, where we used form of events to get an event stream, switch to an interval stream using switch map, but the interval only fires once every two and half seconds. If I click "Start", we don't see anything happen for two and half seconds. There was quite a delay. Let's add an immediate event as soon as we click. We'll import startWith, and then, we'll include startWith in the pipe function. We'll start with the event with the word start. Let's actually move it below the Map function. The first event will just be start, and then the next events will show which click it was and what the event number it was. Now, if I click on "Start", we see start appear immediately, and after two and a half seconds, we see the events come by. If I click "Start" again, we see start appear immediately again. The startWith operator's probably not the most common operator, but it is quite useful. I've got a fair number of places where I actually used this in my code. See you in the next video. 28. Custom Operators: Hi there. Welcome back to this course on Master RxJS 6 Without Breaking a Sweat. In this video, we're going to take a look at creating custom operators. Creating custom operators is quite easy and quite useful. The best way is to start with one of the standard operators. If you're really doing something which is more specialization of one of the standard operators. Start their re-used at and you're done really quickly. If you need more flexibility, grading and observable using observable dot create is the way to go. So let's take a look at the code. Here I've got the example we did before when we were filtering on prime numbers. I'm basically using the filter operator, checking for prime numbers and this is the function we're actually calling. It works like a charm. Let's assume we want to use is prime more like an operator instead of something we call in the filter. So use it like this. If I just try to call it like that, we'll get a run-time error. It's not an operator yet, it's just a simple function. But turning this function into an operator is quite simple. We start by importing the filter operator and we just return to filter operator with the parameters needed. In this case, it gets number being passed in. and we return whether that number is a prime number or not. It works exactly as you would expect. Really simple. Basically all we did is just moved to filter operator from the inside of the pipe to a separate function where it's reusable. Suppose you need to be bit more flexible and just using the standard operator doesn't cut it, we can start with using observable dot create, again will export a function but now we'll use observable to create, to subscribe to the parent observable. So the parameter source is a source observable we'll use and then observable dot create restarts, subscribing to dots and listening to the event and emitting whatever we want to emit. In this case, all the prime numbers. So we implement the first parameter to subscribe to next handler. Every time a number is emitted, we check whether it's a prime and if it is we emit it again on this observer. Fixed my typo and the artists, we get the prime numbers again. This is almost correct. The thing that's missing is handling error and the facts that the observable close. Let's add the error handler and the Complete handler as the second and the third parameter. Again, we're just going to pass everything on to the next observable. No need to handle anything specific here and everything still works. In this case, we're not actually doing anything with errors or completions. So we don't see a difference when running it. Creating custom observable operators is really easy. If you can reuse a standard Operator, good for you, do it, it's the easiest way. Otherwise, just create a new observable and emit whatever you want to emit coming in from the input. Possibly updating value filtering values, or maybe emitting even more items. See you next video. 29. Testing Operators and Observables: Hi Maurice here. We'll come back to this course on Mastering RxJS 6 Without Breaking a sweat. So in this video we are going take a look at testing operator and observable streams. In some simple cases like the prime number operator, a simple standard unit test will actually do. But in many cases that's not quite enough and we want more. So it is a really useful library on npm called RxJS marbles, which is a marbles testing library. So you can describe the stream you expects as a marble diagram. You can actually test whether the resulting observable is what you expect. Really easy to use and it worked with a lot of different testing frameworks. I'm going to use Jest, but it will work just as well with Jasmine or EVA or Mocha. So let's take a look at the code. Here, I've got two prime operator we created in the previous video. I'm using the simple version, just extending the filter operator and just as a reminder, when I run it, I click Start, we see all the prime numbers appear. Great. So let's write a unit test for this I already have just set up. So if I run this and I add the dash, dash Schwartz options, so just stays active 14 to source files and we run tests as needed. We can actually start testing. So you can see there is already a test file there is primed to test all jest but there is no test in it, so just actually fails. It expects a minimum of one tests. Let's do the simple thing first, you standard RxJS operators and observables and Jest testing capabilities. So no additional libraries required. So we'll use the range to create a range of numbers and I'll use to reduce operator, to reduce that into a single array we can test against. So we'll create a range starting from one with the number five is prime function and we'll use to reduce that into a single array. Our subscription will only fire once with complete results. So let's test if the resulting prime array is equal to a known array. So we'll add the numbers 1, 3, 5, 7, and 8. So we've actually got a failing test here because 1 and 8 are not primary number. However, if we look at a Jest output, we see the test run and it passes. It doesn't fail. Why is that? Well, the test is asynchronous. Observables are asynchronous, so the expectation concludes after the tests as already finished. So by adding the don't call back, we can actually make sure that Jest waits for our test to complete. Now we see a failing test. We can see that 1 and 8 are not expected but the number 2 was expected because that is a prime number. Let's update the expectation. Change 1 to 2 and remove 8 and our tests are going to pass. There Jest runs and reports are tests as green. Great. Now simple case like this, this would actually work, but if we want to test a bit more than this is not going cut it. A really useful library when testing RxJS operators and streams RxJS marbles. So let's import marbles and let's create a new test, testing For prime numbers up to 10. We have a new test, but instead of providing a callback, we're going to wrap the callback inside the marble function. It will give us a context which will let us create observables and test observables. So using context.cold I can create a cold observable and here I describe what my observable should look like. So every position is a 10 millisecond window. So we're going to wait 10 milliseconds, emit 1, wait another 10 milliseconds, emit 2 etc. All the way up till 9 weights, 10 milliseconds and then the vertical pipe means close the observable. So that's our input numbers observable. We can create the similar-looking expectation. So the prime numbers observable. It's the same string, except now we will move to one for the 6 to 8 and the 9 because those are not prime numbers. So now I can create a resulting observable stream by using the pipe is prime operator on the number of observable and that should return only prime numbers. So using the context dot expect, we can test whether that results is our expected prime number observable. There Jest runs and we have a passing tests. Now I always like to have a failing test. Little paranoid I wanted to see my test fail. It's pretty easy to write tests that don't fail. So let's record nine as unexpected prime number, which of course it isn't and we see the test fail with the number nine more being emitted but expected exactly as we expect. So let's remove it and our test is green again. So these works but is pretty simple. In fact, if we want to start emitting higher numbers, we can't do it this way because every digit inside the marble stream is something being emitted. So if we want to emit higher number, we can do so, but we need to add a second parameter to the contexts.cold when we create the observable, which is the actual value. Some grading of values object with A being 11, b 12, etc. Then in context.cold, I'm going to emit A, B, C, D, E and when an A is going to be emitted, it sees that there is a value, A on the values object, and it will actually emit the value instead of two digits listed. That way we can emit everything we want to. So we can create the expected primes observable in the same way. With of course, B, D, and E are not primes because 12, 14, and 15 are no primes, so only A and C are leftover. Now when we run the test using Jest, it passes. This is really nice let's switch for a moment from the simple implementation to the operator using observable.create. We see the test still pass. But now if I forget or make an error with completion, our test fails as well, because with the vertical bar in the observable, it actually denotes the closing of a stream. So it expects a closure, but it doesn't happen because we made an error in our operator and our test fail. We are not testing within error condition, but if we did, exactly the same would happen. So fix that cord and the test is green again. So creating standard unit tests can be useful. It was useful in a simple case like this. But in many cases where you want to test more than just a single operator with the single value, then you need a bit more in the RxJS marble library makes it really easy. Work with lots of different testing libraries. Works on observable strings, not just a single operator, and makes it really easy to test everything. So see you in the next video. 30. Scenarios Introduction: Hi, Maurice here. Welcome back to the course on Master RxJS 6 Without Breaking A Sweat. In this section, we're going to take a look at different scenarios where you might want to use AJAX and how to apply it. A couple of the different scenarios we're going to take a look at is handling errors, incremental search with AJAX requests, where we want to prevent duplication of requests and file move to many, periodically polling an AJAX API and displaying results, creating a bank-like application, or using a Redux like data store. There might be very different scenarios you're interested in, and some of them I might not have covered. If you let me know. Just send me a message. Leave a feedback in the Q&A forum. Then I might just add those scenarios. If it's an interesting thing for other users and I've got time, I'll certainly add it. Just let me know what you are interested in. See you in the next video when we'll start with the first scenario. 31. Preventing Errors from Completing an Observable: Hi, Maurice here. Welcome back to this course on Mastering RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at how we can catch errors that prevents the observable streams from being completed. By default, if an error occurs from observable stream, it's going to emit that error and close to string. Using the catch operator, we can actually catch these errors and replace the stream with a new stream. But your original stream is still going to be closed. Nothing you can do about that. By combining multiple streams, we can actually recover from this by closing a secondary stream and keeping the original stream up and running. Let's take a look at some code. Here I'm handling the click event from a button, usually from event handler and I'm using the merge map operator to merge in a new stream, which wrote error, reporting that something bad has happened. If I click Start, we can see the error or something bad happens and then when I clear and try to start again, nothing happens. The original observable stream from event was closed. Let's introduce the catch error. The place where we add this is important. If I add this to the pipe from the original click stream, it's going to catch the error, but it's going to still close that stream. With the catch error, we return a new string. In this case, I'm going to return the string with a single event. We see the observable stream didn't error anymore but completed. If I clear and start again, nothing happens because it's still completed. In this case, we want to catch the error on the stream where it occurred and not on the mainstream. On the stream which produces the error. Now if I click start, we see the message from the the catch operator but we don't see the original stream closing and if I clear, we can press start again and we'll see a new message from the catch operator so the original string remained open. Keep in mind that any error will complete the stream they occurred in using catch error, you can catch the error, but it still closes to stream. Combine multiple streams using merge map or switch map, or one of those operators in order to keep the original stream open and still handle errors. See you in the next video. 32. Retrying Errors: primary share. Welcome back to discourse with mustering RGs six without breaking a sweat. So in this video, we're going to take a look at retrying actions that produced perish. So some actions can produce errors, which are fixable by a simple retry. No to bleeding. Ajax requests. If I do a http request, fetching from data from the sheriff for that server might be temporarily down or my Internet connection might have failed. I might be on the mobile device going crew tunnel or something like that. So there, to operators we can use to retry, was to retry, which does so immediately for a number of tons. And the mystery. Try Win Operator, which takes a nested, observable string and will retry when that national observable stream complete. So foreign Ajax requests doing immediate retry. It's typically new, not the best idea, because it's not gonna pause. It's gonna send multiple requests to the server very rapidly. And if the server is failing because it's busy, that's pretty unlikely to help. So retry when with a slight force, is typically a better approach. So let's take a look at some coat. Have a good time coat when we click I'm doing an Ajax told agitation to an A P I request. That doesn't actually exist, going to my server and offering for something that doesn't exist. So that's gonna feel with a 40 for North funds, no air handling whatsoever yet. So if I click to start button, we see the request occur and fail with the 404 North funds. If I click again, no other requests are done like the observable is death. So let's import to retry operator and you that first of all, just like catching errors. The location where you re try in the chain is important. If I had to retry after the switch map and I click start, the only thing that's gonna happen is we're going to retry to switch map that doesn't actually do anything for useful. If I click multiple times, we can see eventually that to request feels so in this case, we actually want to retried get Jason. So we need to add to pipe function there and to retry to that So the gadge Asian is retried . Now if I click start, you see four requests in rapid succession, one initial request and three retry. But like I said, this difficult is not the best approach with Ajax requests. So let used to retry one to retry winrow chief, the airshow weaken very our behavior, depending on the error. In this case, I'm just going to use to Interpol and emit once every second. Which means that the get station will be retried once every second. So when I click start, we see multiple requests occurring. Basically request every seconds, and it just keeps on going. It never folks. That's because the interval keep from taking. So if we want to limits the number off retry. We used to take cooperator and we just take the 1st 3 events so we'll do one initial request and then three return Try requests with seconds in between. There are four requests. No, if I click start again. It didn't feel the observable string, so it starts doing requests again. So what? Certain errors Retrying is a very useful strategy, especially Ajax. Request using to retry when operator is typically the better approach. So see you in the next video 33. Incremental Search: Hi, Maurice here. Welcome back to this course, Mastering RxJS 6 without breaking a sweat. In this video, we're going to take a look at doing an incremental search by typing into a text box and then filtering some data on an AJAX server. We'll start with a DOM event, we'll map that into the value we're interested in. We'll do an AJAX request and it will display the result and we'll add some nice to have features like throttling the number of requests, filtering out errors and invalid requests, etc. All stuff that's relatively easy to do with RxJS. Let's take a look at some code. Here, I've got the surface we're going to use, it's a GitHub API which lets us retrieve users based on their username. Here's the example when I search for Torvalds. Here's what we're going to get started with, we've got a search input and anytime we type, we see the events being printed to the console. We use the form events and tap to achieve that. We're not interested in the whole event, just actual name. The first thing we'll do is use the map operator to extract the actual value from the event and there we see the values being printed out. Currently, we get some output for every change made, every character types and if we turn every character type into an Ajax request we would be using the GitHub API quite heavily and all the intermediate results are not going to be displayed anyway. Let's use the debug time function to prevent making an Ajax request until the user has paused for a second. Now, if I type my name in, you only see the outputs after I've paused for a second. If I clear the output and type Torvald, we see Torvald and then after a pause and then if I type DS, we see the full Torvalds but still after a pause. Let's turn this into an Ajax request. We'll use a switch map operator to turn the user name into a search request on the GitHub API. Now, if I open up the Network tab and I type my name into the input box, I see your requests to GitHub for my user and if I change it to Torvalds, we see another request. Great, so the response we get back has an items property and we're only interested in the items, so let's map that and discard the rest of the response. Now, we just see an array of items but we actually want to process the users one by one, in order to display some UI. Let's use the merge map, which turns a collection of an array of users into individual events of users. If I type my name, we see a list of users being emitted. It's actually uncommon to code and subscribe so we get some nice UI. We'll get the bootstrap card for every user being returned. If I type my name, we see me on the second item and others. Now, if I type Torvalds the request is made but it's basically being added to the list, we want a little side effects. Before we search, we actually want to clear the results, we'll use depth operator to set the inner HTML of the result div to empty, so the previous result is cleared. Now, if I type my name, we see me and other users with similar names but if I type Torvalds, we actually get to see Linus Torvalds and other people with a similar name. Another issue is, if I make some changes but end up with the same value after a second, so I'll remove the S and add it back in. We actually created a second request which is exactly identical as the previous request, so using the distinct until change operator we can prevent that won't emit the same value in sequence. If I search for Torvalds, we get to see Linus but if I remove the S and add it back, we don't do another request. Only until I actually change the value we searched for and pause long enough for requests to trigger, that we do make a request. If I removed a value, we see that there's actually an error from the Ajax request. Now, if I type, nothing happens, we've killed the observable, we need to add some error handling again. Only get JSON, I'll use the pipe operator and the catch error operator to turn that into a different strain and in this case I'll just use an empty string because there is nothing to see. This will catch the error on the Ajax stream and keep the mainstream intact. Now, if I search for Linus, I'll find him, if I empty it, request is made but an error is returned. If I type my name, the observable was still okay, we could still search. Still, it's better to prevent that error. The error is actually a result of searching with an empty username, so let's use the filter operator to prevent searching for empty usernames. We'll use the double note operator to make sure that the user is not empty. The search for my name, we get the results, empty things out, the screen is blank but we don't do an Ajax request. Pretty cool. Doing an incremental search using RxJS is quite easy. We used handful of operators but they all played together really nicely and managed all the state for us much easier than doing this with imperative code. I really love using RxJS in cases like this. See you in the next video. 34. Polling Ajax Requests: Hey, Maurice here. Welcome back to this course with Master RxJS6 Without Breaking A Sweat. In this video, we're quickly going to take a look at creating polling Ajax requests. We're going to do Ajax requests and we're going to keep repeating the requests on a time-based interval to show the user the latest data. But we're going to start with a timer event, and just like in the previous video, we're gonna do an Ajax request and display the results. Let's take a look at the code. This is what we're going to use it a dataset, Chuck Norris database. It has a RESTful API where we can get the set of random Chuck Norris jokes. In the previous video, we used from events to start to request. Now you might think we'll start with the interval, but if we use the interval, you'll see that we actually have to wait. I've specified five seconds and it actually takes five seconds before the first request is done. A better way to start is with the timer, with the timer you could specify the initial wait time 0 milliseconds, and then optionally how often it should be repeated, so I'm using five seconds for repeat interval here. As soon as the page loads, it fires off an Ajax request gets the first ten jokes and then every five seconds it repeats that, so pretty nice. Creating polling Ajax request is quite easy, Pretty similar to doing it on click event or something similar. We use pretty much the same operators as last video, the ajax, catchError, the EMPTY, mergeMap, switchMap, tap and in this case we started things off with the timer. See you in the next video. 35. Drawing on a canvas: Hi, Maurice here. Welcome back to this course on Master RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at drawing on the canvas. We already did draw some on the canvas, but now we're going to make it a bit more explicit. We'll start drawing when we press the mouse down. We'll keep drawing as long as the mouse is down and we move to mouse. But with the mouse up, or when we leave the canvas, we'll stop drawing. Let's take a look at the code. Just as a reminder, here's the canvas we had before. If I move the mouse over it, we draw. This was the original code, and we basically started with the mouse move events, and we started drawing. Now we want to be a bit more explicit. We wait for our mouse down events, and only with the mouse down, we start drawing. Add another observable stream for the mouse down event, and we'll actually subscribe to that. We'll use a switch map operator to switch from the mouse down to the mouse move observable stream whenever the mouse is done. Now, if I move the mouse, nothing happens, but as soon as I mouse down, I actually start drawing. Except when I release the mouse, it's still keeps on drawing. We still need to stop drawing. We'll add a third observable stream for the mouse up events. We'll import take until operator, and we'll take mouse move events until we get a mouse up events. Now make sure to add take until in the mouse move events stream otherwise, we'll stop the whole event stream. We just want to stop the mouse move and still listen to mouse downs to start new draw events. Now I can draw, I can stop drawing, and everything looks fine. That is until my mouse leaves the canvas. Even if I release the mouse button outside of the canvas, it still keeps on drawing. If I leave the canvas, we also need to spoke drawing. I'll create an observable for the mouse out. Add stop using the take until operator. Now, drawing actually stops when my mouse leaves the canvas. Pretty sweet. Drawing is pretty easy. We already have the basic drawing code. By using the switch map and the take until operator we made it more explicit. Only start drawing when the mouse is down and stop drawing when the mouse goes up, or we leave the canvas. See you next video. 36. Painting: Hi Maurice here, welcome back to this course on Mastering RxJ6 without breaking a sweat. In this video, we're going to continue with the Canvas and we're going to expand drawing to include some more painting-like functionality. We'll startWith the drawing example from the last video, and we'll add observables to specify the color and the line size of our drawing. We used to combine in the withLatestFrom operators to insert those into the observable stream. So let's take a look at the code. So this is basically our previous example where we can draw on the Canvas. But I've included the color and line inputs. But right now they don't really do anything yet. So let's startWith the color. I've got a reference to the input called stroke style. So we'll create a new stroke style stream using fromEvent and we'll listen to the inputEvent. So I'm using the standard HTML5 color input control there. So we're only interested in the value show all use the map operator to get the value from the input. Just like we've done a dozen times before. Now I want to inject that into the stream, we listened to for painting. So convenient operator to use there is withLatestFrom, where I can combine different input strings into one stream. So I'll combine them. mouseDown stream, which a strokeStyle stream, and the second parameter is the function to combine the different values, not interested in a mouseDown event, so we'll ignore that, and will take to stroke style and turn that into an options object which has to stroke style will add more to that later. She's now in the switch map, we get that options object with our stroke style. So I'll add that 2D object created, which means it's just like to form objects. So I'll grab the options from there in the subscribe and set the context stroke style, do whatever stroke style we specified. So now if I select the color, red for instance, I can draw a red line. The only problem if I refresh the page and I start drawing, nothing happens, because we got no initial color yet. So we need to make to stroke style stream a bit smarter. You have to specify that it starts with the initial value of the input. So we'll just specify the initial value there, and now it starts off with the value so we can draw right away. We can draw a black line, and now I can change it to blue and we can draw a light blue line or more purple. Sweet. Let's do the same with the lineWidth. The approach is the same, so I'll just copy that stroke style string and change the variables to use a lineWidth. Note withLatestFrom operator is really convenient. We can use as many input streams as we want. So we'll add the lineWidth stream to that and add that to the options objects. Now in our subscribe, I can just set the lineWidth on the context, simple. Now we can just start painting. But if I make to line size a little bigger, we get a fatter line. If I changed the color to red, we get the fat red line, Nice. So [inaudible] we're experts. I kind of don't like duplicating that input string. But let's creates a little helper function, get input string and we'll pass in DOM elements and it will return a stream of its values used to elements being passed in, and now the stroke style stream is the result of calling get input string. We'll do the same for the lineWidth stream, and everything still works. Nice little helper function. So adding paint like functionality is pretty simple. We just add inputs to take whatever property we want and we'll use to startWith and the withLatestFrom to grab the value and to embed them into the stream we used to paint, sweet. So see you in the next video. 37. Sharing Subscriptions: Hi, I'm [inaudible]. Welcome back to this course on Master RxJS 6 without breaking a sweat. In this video, we're going to take a quick look at sharing subscriptions. Sometimes you need to share subscription because in most cases, every time you subscribe to an observable, it will create a new observable and execute all the code in the observable again. Now that isn't always the case, but in most cases it is. The share operator will let you actually share all the code in an observable. So it's only executed once for every subscription. That makes it faster. Let's take a look at some code for an example. Here I've got our fetching example again where we were searching for usernames on GitHub and I typed Torvalds. We see a list of users appear and a single Ajax Request being done. Part of the request is the number of users returned, the total counts. So if I include that in the result counts, now we see there were actually two Ajax Rsequests done. That's because were subscribing to the event stream twice. So everything in there is executed twice, including the Ajax code. Now that's kind of wasteful, so let's do a single Ajax code to get both results from that one code. We'll import the share operator, and we'll add the share operator to the pipe. Remember you add this at the points where everything before that you want to share between all subscriptions. So I'm adding it after the Ajax code in this case. Now if I search for Torvalds, we get the total number of users 126 and the list of users with a single request. If I search for my name again, a single request for the total number, and the users themselves, much better. Sometimes it's best to share observables if you'll do multiple subscriptions. It isn't always necessary, but quite often it is. In this case, it was very clear that the Ajax request was being done multiple times. It isn't always that clear. Basically the operator to use is share. There is a relation to operator shareReplay, which is a bit more advanced and will actually remember values and re-emit them when new subscriptions are made. We'll use that in another video. See you in the next video. 38. Redux like Store: Hi, Maurice here. Welcome back to the score from Master RxJS 6 Without Breaking A Sweat. In this video, we're going to take a look at creating a simple Redux like datastore. Redux is a predictable state container for JavaScript. Very popular, especially in the React world and is very capable and extendable. We're not going to make it quite as advanced. We're going to do a very basic implementation in RxJS because it's actually pretty simple to do. Let's take a look at the code. This is the actual Redux site, so the predictable state container for JavaScript. You will learn more about it, I highly recommend you visit these sites. For a starter, I've got a little app with an increment and a decrement button and an add 10. Here you see the code, the event handlers for increments and decrements. You see we import a reducer and a createStore function, and we call the createStore possibly in the reducer. Then we subscribe to the store and we actually display the current states as a formatted JSON string. We also subscribe to the different buttons and dispatch actions. You can see the actions they're basically objects with a type denoting the kind of action, and in some cases like in the add 5, it has a payload containing additional data. In a typical Redux scenario, these actions are created using helper functions, but in order to keep this example simple, I didn't bother to do that. But it does make it more reliable and more testable, so highly recommend that you do. Reducer is really simple. It basically listens for actions and returns a new state whenever the action modifies the state. One of the core principles is immutable data. You never change the state, you always create a new state object. That's what I'm doing in the increment and decrement functions. I'm basically creating a copy of the state object, setting the count, in this case there is nothing more in it, so pretty simple. But if there was more data in it, it will be preserved and JSTOR account would be updated. The switch statement like this is not very functional, but it's the way Redux code is written quite often. I'll show you how to make this more functional in a moment, but for now we'll leave this as a simple switch statement. One more thing to note here is that the first time this will be called, the states will be undefined and the initial state will be set as the current state. That's where that initial state variable is used. The signature for a reduce function is very simple and always the same. It basically it returns a new state which is the result of applying an action to the old state. So new state is old state plus action. Simple. The createStore is pretty empty. There is a createStore function which we export but there's nothing there yet. In this case, we want to control how events are emitted so the subject is a good way to create new observable. So we'll create an action stream because it's basically a stream of actions being emitted, which is the result of a subject. Then the store is actually the result of working with the current state and the actions. We used a scan operator to actually compute the current state. With the scan, we passed a reducer function in and we set its initial value to be undefined. That way the reducer is called with undefined as the first state, which will cause to the initial state in the reducer to be set. That way all the responsibility of what's actual state and how it is updated is inside of the reducer and not in the more generic createStore. So we return to store. We need to be able to dispatch actions, so let's add a dispatch function to the store. All it does is basically emits those actions onto the stream. Now if I click "Increment" or "Decrement", we can see the state change. The only thing is there was no initial state yet. So let's start by emitting one events to initialize the state. We'll use the startWith operator and before the scan will actually dispatch one event. We'll call it with type underscore underscore, in it underscore underscore. Name doesn't really matter as long as it's unique and it's just meant to initialize the state. So now see the count start with zero. One more thing, this is application-wide state so it should be shared by all subscriptions. We'll use the shareReplay. Notice share operator protects the shareReplay, so new subscriptions will actually get the last version of the state. We're passing 1 because we just want to remember one last state event, not all the different intermediate ones. It still works. Great. So let's make this reducer a bit better. Because switch statements like this are nice and that's what you see in a lot of Redux examples. But we'll make it a bit more functional because RxJS is more about functional style programming. We'll create a dictionary with handlers. I'll add an handler for the increment action. This only takes the old state as an input. We don't care about the action. There's nothing of use there. We'll basically return the new state from there. Do the same with the decrement. We need to put these in brackets for it to return that object, otherwise it will be considered a code block. So let's include the decrement. Now we don't need to switch statement anymore, but we can do a simple lookup in the handler for object to find the right handler for a specific actions. Once we have that handler we can execute it with the old states and the action returning the new state. Now there might be actions triggered which we don't actually handle, like that underscore underscore in it underscore underscore action. So let's add a default handler which just returns the current state. The handler is the one for type specified or the default one. Our behavior is still the same, but the code's more functional now. Now let's add a new handler for the add action. We'll create a handler called ADD. It takes a state. It also takes the action because the payload in the action will indicate how much should be added to the current state. Instead of plus 1, we add the action to payload to it. Now we can still increment and decrement, but we can also add 5. Recreating reducers this way is much nicer. We get very small testable functions. These guys I didn't export it but we can just export those handlers and make them very testable. So doing state management in a Redux-like style with RxJS is very simple. We created a new stream using the subject. We basically used a scan operator to compute the current state based on the previous state and the action. We used startWith operator to initialize the state and we used the shareReplay so new subscriptions will automatically get to current state and the state between all subscriptions is shared. Pretty sweet. So I'll see you in the next video. 39. Redux Store Subscriptions: Hi Maurice here. Welcome back to this course on mastering RxJS 6 without breaking a sweat. In this video, we're going to enhance the Redux store a bit. We're going to add RxJS 6 style subscriptions to it, so we don't have to just use imperative codes to dispatch events. This turns out to be rather easy because the subject which we used to create an observable stream, is also the right shape to act as a subscriber. You can just push that subjects as to subscription of events streams, and chain the different streams that way. Let's take a look at the code. Just as a reminder here we have the previous code. I've got an increment button at five and increment. If I click increment, we see the count increase, and the same with the other buttons. Instead of fusing add event lister, I want to do this in a more reactive style. We'll use the from events to create an observable stream of click events, and we'll use the map operator to create the action object we dispatched. Then we just want to subscribe to store to this event stream. Now I can't just pass to storing, that won't work, because the store is not the actual subject. If we look at create store, we see that the store is just a result of piping event Struger, action stream, and the action stream, that's the one we actually need to subscribe. We can add that to the store exposure that way, then we can use it in the subscription. We'll subscribe using store stream dot action stream. Now we see the increment still works. Of course, plus five and the decrement still work. They haven't changed yet. Let's update them in the same way. Let's copy the code and update the action objects and the event handlers. That's the decrement done. That's the plus five done. I will see all the event handlers work. Nice. Using a more reactive style with RxJS is really simple, because it's all observable streams we can just chain together. Sweet. See you next video. 40. The end: Hi, Maurice here. Welcome back to this course on Mastering RxJS 6 Without Breaking a Sweat. Congratulations, you made it. You've reached the end of the course. So hopefully, you've seen that RxJS is a great library. It's great for asynchronous reactive programming. Use observable streams, manipulate those streams using operators, merging, streams filtering, transforming, et cetera. Lots of capabilities. So now it's up to you. Go on, build something great using RxJS, and let me know what it is. If it's something public facing and I can see, I always like to see what people make using the techniques I teach them. So this is the end of this course, but there is always more to learn. For anything more you want to see in this course, for more scenarios or maybe operators who want to see covered, let me know. I'll add them and I'll notify you when it's done. We'll learn something else about reacts, or Angular, or GETs, or any of those things, I'm game. So just let me know and I'll take a look at it. So good luck. All the best, and have fun with RxJS.