 bit about functional reactive programming in JavaScript, more of a FRP inspired system in JavaScript. We'll see how we can use FRP to change the way we write asynchronous code in JavaScript both on the server side and on the front end side. So before we get into FRP, I would like to share a story of a dear friend of mine, a software developer always chasing JavaScript like all of us. He never caught it though, neither do most of us. So he was given a task, he had to render some tweets to a web page, a very simple task, right? So he made a small assumption about his task, he assumed that he has an array of tweets of 100 or so tweets and he had to render them to the web page. Now he is an awesome developer, so he divided his specs quite clearly into three requirements. The requirements are he has to show the tweets for the single user only, the selected user only and he has to show that only those tweets which have a particular hashtag and he has to replace the text emojis in his tweets with images. So he starts with his development, with his solution. So he takes the source, tweets from the source and he do the first operation, the first task. He uses filter for that. Now filter is an array extra function. It takes a function, execute that function on every item in the array and creates a new array with those items for whom this function returns true. So basically filtering the array, creating a new array. Notice we are using arrow syntax here, fat arrow syntax. It is just creating a function with one argument t and returning the statement. So first problem is done. Now for the second, he has to show only those tweets which have a particular hashtag. Quite simple, just another filter. So he does. For the third problem, he has to manipulate the tweets now. So for that he uses map. Now map is just same as filter but in that it takes a function, execute it on every item and then it creates a new array with the output of product of this function. So he has all his three problems solved. So next the cherry on the top, he has to render them for that he uses for each. So his problem is solved and quite beautifully so. Now he is proud. He think he has written very good code and he is right I think. Look at his code. His code has no dangling state around outside the operations. Each operation is fully contained. So the code is stateless. Stateless code, easily maintainable code and it is composed of smaller operations to do the whole thing and it is still further composable. And the code is not mutating the source. It's a big thing. If you mutate the source, it becomes very hard to test the operation. So you mutate it every time. How do you test it? So these functional properties, these functional things bring a lot of value to our code. So his whole operation looks like something like this. He has a source. He has a bunch of operations working on the source and that manipulates the data and then takes the data to the sync. So he took the tweets, do a bunch of operations on the tweets and then rendered them. Put the manipulated data to the sync. Now these operations are special in that they do not mutate the code and they do not depend on anything outside themselves. No dependency on the external state. In other words, these are pure functions. For just to be safe, the emojis here might not be a pure function, but let's assume that it is. So these functional properties, these pure functions bring a lot of value to our code. For once, the code becomes very much readable. So you can just look at it and say that there are four separate operations and just understand it in one go. Assume if it was in a big loop doing a bunch of things, if this, if that. Next, the code is maintainable. Now there is no dangling state. The code is highly readable. You will be a lot less afraid to touch this code in future. And it is testable. Pure functions are easiest to test. You just pass it the right input and you will get exactly the same output every time you test it. And it is extensible. It is composed of smaller operations. And if we want to add something more, we just add another operation to it. For instance, he is rendering each tweet one at a time. If we want to do it in a bulk, it is just a matter of adding a reduced operation. And it is reusable, of course. He has to create a smaller operations for the whole thing, which makes it obvious where they can be reused. But it is JavaScript and the only dreams that come true in JavaScript are the nightmares. So the reality bumps in eventually. And it is not pretty. So turns out the source that gives him the tweets is not really giving him an array or something. It gives him one tweet at a time and it is asynchronous. So he makes a request somewhere and gets one tweet at a time. So now all his functional awesomeness, the composability and all goes to the sync with the data. So what options do we have here with the asynchronous data that he has now? So first option is using callbacks. You know, callbacks are pretty. Very pretty. So pretty, you need eyebleach just to keep your eyes from bleeding. But the problems with callbacks are real. So first thing is the composition is out of window. How would you compose a synchronous stream inside a synchronous stream? Pretty hard to do. And the dangling state in callbacks is more than nasty. Just assume you are five levels deep in callbacks. And the number two callback said something. Number four callbacks use it. Not debug. Not funny. Okay. And the code is pretty hard to read. So hard to read, dangling state, not really maintainable. And testability is like, yeah, it's a joke. Okay. The second option he has is to use a promise. Now promises are awesome. They are awesome in that callbacks treated asynchronous values as a bastard child of JavaScript for ages. Promises made the asynchronous values first class citizens. We can pass them out as arguments, keep them in variables until we need to get the real value. But after a line is crossed, promises have same problems as callbacks. Almost same problems. First, they are hard to compose, quite hard to compose. And they resolve exactly once. Once a problem, promises resolved or it has given an error. It is pretty much useless after that. And canceling a promise in a pool of, say, 100 asynchronous requests is not something you would do on a sunny weekend. Okay. So maybe it is time to make a compromise. Now he has to use asynchronous source. So he has to make a compromise. Either he uses callbacks or he uses promises. In either case, all his composability, the readability, all the awesomeness that those functions brought is gone, right? But no, he lived a life of no compromise. He won't compromise, not in the face of callbacks. So what he does instead is stood up and jumped out of his window. No choice, right? Windows reminded him of another awesome technology from his favorite corporation, not ECME. So Microsoft has this awesome thing called RXDS. These are the reactive extensions for JavaScript. Now, reactive extensions have been in C-sharp forever. But they have brought it over to many languages now, including C++, C-sharp. It already had them. Objective C, Java. And maintained by Microsoft. So you can say that it is not something just a toy. And learn once and implement everywhere is the trend, right? React Native. So, yeah, you can learn RXDS in one of the languages. And semantics are pretty much same in most of them. So how would the code look like if he had used RXDS instead? All the asynchronous code. Now, he has a source which returns one P asynchronously. So something like this. We converted the source which gave a promise to an observable. Observable is the central piece of RXDS. And then he, I just, I think I copied the synchronous code. Did I make a mistake? Is it the same code copied? So it was a mistake, right? What if it is not? What if you can write the synchronous code just like this? Now, this is a synchronous version. And this is the supposedly right, maybe wrong, asynchronous version. Almost exactly the same thing, right? So maybe the observable is the unicorn which allow you to write the code in this flowing fashion using pure functions and all, keeping all the awesomeness of your functional code. Maybe. Okay. Let's look at this unicorn. Okay. So an observable is a data set, a set which updates over time. So like promises is a value which gets its actual data from future. Similarly, observable does the same thing. Do the same thing. Now, these are the building blocks of functional reactive programming inspired systems in RXDS. FRP is not really possible in JavaScript. It is not concurrent. But it is a FRP-inspired system and quite beautiful. We'll see. And they are like promises. They make asynchronous values first-class citizens. So you can pass these observables around in functions, compose them together. And they have a very good functional grammar, like array extras. We have map, filter, and all that. Observable provides similar operators and a lot more than array extras, which allow you to compose them very well. And they play really well with other sorts of data that we have. So but why should you care, right? Now, observables are awesome. Of course, you should use them. But why bother? We don't like new things. So why you should care? The first thing is that there is a proposal to make observables native in ES7, like promises are native in ES6 now. So hopefully observables will be in ES7. And Angular 2 supports them. They are integrated into Angular 2. So if you really want to master that thing, I hope most of you do. You need to know this. And the new hot kit in the town, it has plans to support them first-class. So now I have you convinced. So what is an observable? So if we take a look at our code from a junior dev's perspective, it is mostly about flow of data. Like we have some data. We do some manipulations on it. And then we do some side effects to it, to show it to the user or keep it in the database or something like that. So how do we represent this data in our day-to-day imperative programming as variables, values in variables? So now in our usual programming, we don't consider time to be a factor. We don't think that time is something. It makes perfect sense though. We deal with asynchronous data often. And we don't have that data always. We get it from future. So if we consider time in our programming, let's call it temporal programming. The programming we consider time. So how do we represent a value in temporal programming? Something which don't have its data yet, but will have in future? A promise, right? But we don't deal with values directly. We keep them in collections. We deal with the plural of values. And that is a table in JavaScript. In ES5, these are arrays. ES6 has more forms of them. So what would be the plural of a promise? How do we represent a collection of observables or collection of asynchronous values? An array of promises is the wrong answer. It is just not the same thing. Now this is the spot where this observable fills. Observable is a, you can think of it as an array which is spanned over time. A collection which gets its values in future, one by one. So then these observables have these operators that allow you to do almost the same stuff as we do with arrays. This is the code which, a synchronous code using an array. And this is a synchronous alternative. Okay? It allows, if you know the array extras, how to use array extras, you already know how to use observables. Okay, now, in my opinion, observable is natural evolution of promise. So if promise is Bulbasaur, what is an observable? Evolve Bulbasaur, of course. Now about the API, the promises have these resolve and reject and then an error while creating and using the promise. Observable has onNext and onError doing the same thing in both the cases. Now it is called onNext because it is a collection. It will get its values maybe more than once. But it is a collection. So it might finish sometime, right? It might have a length. We don't know it yet, but it will at some point. And when it completes, we have this uncompleted callback. So all these three things together, they are called an observer. So observer is, say, as important as observable. I didn't mention it earlier because we don't usually create observers directly. We have a subscribe method on an observable to which we pass either one of these three, two or all of these three functions, callbacks, and Rx just creates an observer implicitly. So why am I mentioning it now? If it is not, we don't really directly use it. Now observables are lazy in that, say, now this code, take an observable and do something with it. Now this code will not execute. It will just stay there. It will not execute until we connect an observer to it with the subscribe method. Only at this point, this code will start executing. And this is a very nice feature. It makes it easy to use the observables very easy. Intuitive, I would say. And there are many operators on observables, like map, filter, reduce, scan, many, lot many. For any case, you might think of. And there are a lot more than this. And we can convert almost anything to an observable, be it variables and arrays, promises, events, callbacks, or even generators. And generators and promises have first-class port in observables. You don't need to convert them every time. And the observables are disposable. Now we convert events to observables. And what's the most common source of memory leaks in JavaScript? Event listeners. We add them, we forget to remove them. Now when we create a subscribe, it creates a disposable. When you subscribe to an observable, we can dispose it with disposable.dispose and it will free all the resources or remove the event listeners and everything. But it is declaratively, we can do this declaratively. We don't really need to call disposable.dispose if we use it properly. Now notice, here I created clicks observable. This observable will have a value every time I click on this count button. But I said that take only five. Forget about this zip thing. I said that only take five clicks from my observable. And after that, it knows that I only need five clicks. And after that, there is no use of it. It will dispose it by itself. So one, two. After this, the event listener is removed. So the chances of memory leaks, if we do it the proper way, are very less. We don't really need to remember to remove all those. And about performance. So observables, RxDS team try its best to keep observables have as little footprint as possible. So because we create an observable, every time we do that map thing. So it has to be like. And swappable concurrency. JavaScript is not really concurrent. But this observables has this thing called schedulers. Schedulers allow you to put your callbacks where you want, like how you want to execute them on the set immediate or process.next click or the way we want. For example, for animations, we want them to be executed on request animation frame. So we can swap them. And when we use arrays, the map, the filter, it creates an intermediate array every time. More work for garbage collector. Since observable is not really a complete collection at any point, it don't create all this intermediate memory. And it supports transducers. So you can even avoid creating observables. And to be any library to be used, it has to play well with other stuff, right? So we can create observables from native events. We can do the same with jQuery or Zepto events from jQuery promises. Just make a jQuery.get request and convert it to an observable or just use it directly inside an observable chain. But we use frameworks, right? So there are bindings available for most frameworks. So you can just add another library and start using observables within your present apps that you're using frameworks. And the company which has created, RxDS has created this beast as well. The IE6, right? So I know most of you have nightmares of it. So the sport for RxDS goes as back as IE6. They have these compatible builds which sport even IE6. So time for some example. First example we'll see is called follow the mouse. We'll create a three-part mouse chain in which the first part follows the mouse immediately. The second part follows the mouse a little delayed, okay? The third part follows the mouse even more delayed and it wriggles. So demo. So here it is. The first part it follows the mouse right away. The second part it comes a little late and the third part comes even late. And it wriggles because it is too happy. Now imagine how we do it in imperative programming. Any proposals? How will coordinate this delay? That the first part is easy. We just add an event listener. Then we have the second part which does the same thing but little delayed. The third part does two things. Sorry? Yeah. Set time out. How will they play together? Like there are three things. They have to happen in coordination. So let us have a look at how the first part is done. Okay? First thing we do is we convert the event to an observable. I use this underscore at the end just to be sure that it is an observable. My thing, personal thing. And then we have to move the position of that block, right? For that we need the coordinates. The x and the y. For that we create another two observables. The left and the top. From the observable we created from the event listener. And then here's that element. And then we simply do set left. Set left is a simple function. We just change the left and right and left and top on the style. So the code is just as simple for the first block. Now second block does pretty much the same thing but little delayed. Right? And set time out will not really play that well. For that in this example we simply just add just one line of code. We call it that say that now my observable is getting these values whenever I move my mouse. My observable is getting these values whenever I move my mouse. But for the second my second block I want these values late. Send these to me but send them after this delay milliseconds. So these say this is our observable that actually comes when we move the mouse. Say it has this one to three what delay does is just delays them. Send these to me a little late. And for the third one we have the same thing delayed and we create another source which give us value between minus five to plus five every hundred milliseconds. Okay? We use interval for that. So it was just a matter of adding four more lines to make the third block becoming late and work well with another interval that we set. Okay? Enough fun. A little bit of more real world example. This auto complete is like the hello world of FRP. Any FRP library that you will see anywhere present it will always have this. So, okay, this is what we want to do. Here is an input block whenever user add something enter something we send a request to Wikipedia and show the suggestions. Quite simple, right? But we have some conditions here that we will not send a request until user has entered more than three characters or more than two characters. Okay? We send a request only after the third character and we don't send a request if user keeps typing something. We don't want to bombard the server. We want to send a request only when user stops typing and there is no activity for some time. And we don't send a new request if the value is not changing. So, if user uses cursor keys, we don't send a request. It is not really as easy as it might look like. So, let's see how we will do it. First thing we will do it is create an observable from the event, right? We want to do something when user presses a key. So, that's what we do. We create an observable from the key up and we take the value of the input element every time he presses a key. Next thing we want to do is that we don't want it to proceed if the value is less than two. If the value's length is less than two. For that, a simple filter. And next, we don't want to do something until we have 200 milliseconds of inactivity. Simple a matter of adding a debounce. Then we don't go ahead until the user's value change. If user's value is not changing, we just keep it up to here. And eventually we make a request to the server. Now this function does just one thing. It just creates a jQuery request and sends it as a promise. That's it. We don't even convert it to an observable. So, what this flat map does is that now we have users entering continuously after 200 millisecond delay. Now we are sending a request to the server. Like first goes, second goes, third goes. Now we don't want to handle each and every one of those. We just want the latest one. This is what this flat map latest does. It will receive all the requests, keep receiving them, but will give us only the latest one. So a quite complicated, not really complicated. It is actually quite complicated when we do it in the real world using imperative programming. So I started using these observables a few months back. Since I started using them, I found some very happy side effects in my code. Like the things I didn't really want to do what happened. First thing was when I start solving a problem, I usually make a monolith. Just something which do a simpler version of what I do. And the second phase is to make it modular to keep adding more information. Now I found that my code was almost already modular. It was just a matter of taking observables and putting them in right place for APIs. Because we are creating streams of flow. This is how one operation is done. And modularizing them is mostly matter of either just put the observable in the right place or split it in the half and sort of that. And the code was reusable. Like I used those left-hand top observables back there. And it is very easy to read code. So I use this mostly on my hobby projects at the moment. So I visit them sometimes weeks later or months later. So the code is very easy to read. Just look at them and I know what it is doing. And all this I get by default. I didn't really had to put any effort to do this. And in conclusion we use doing the synchronous programming. We got the same benefits as doing synchronous programming using arrays. Like our code is composable. We write the code in a flowing fashion. There are smaller operations working in coordination with each other. And it is readable. So it's maintainable. And RxJS actually has a great error handling. So any time an error happens at any of those points the error callback is executed and the observable stops. It is actually the killer feature of FRP, RxJS which made me choose it over CSP for playing. But it's more of a homework. So using RxJS we got elegant declarative code, a synchronous code. It is a synchronous so it came lit. So yeah, I hope to see some of you on the dark side. Thank you.