 handle and I work as an UI engineer in the customer experience team in flipkart.com. So getting into the talk, let's talk about JavaScript. Among us we know that JavaScript operates on a single call stack. What does this mean? This means that if a function is occupying the call stack currently, your execution is blocked. But we need JavaScript at least in the front end to do a lot of things. You need it to listen to events. You need it to listen to server calls or WebSocket events. You need to make HTML mutations and so on. But some of these functionalities for JavaScript cannot be synchronous and so we have async tasks. So what do async tasks do? Async tasks have a registered an event listener on an event or register callbacks on the return of data sources and these callbacks get executed whenever the event happens. This for doing this, callbacks are very integral to what JavaScript has been doing. But if you are writing a reasonably large application, you will see that callbacks have their own problems. If they're unstructured, if you're injecting anonymous functions into your callbacks, I mean, so then your code complexity increases as your functionality increases. And also since it is not that maintainable, you will not be able to reuse this code across your application. So what can be done about this? Let's first see an example of a callback. So I think this kind of code is, everyone of us would have written at some point on the other. So we have an Ajax call, a jQuery Ajax. It will make a server call to that API. I want my application to know that the server call has completed successfully. And so I have that ease loaded variable. So this is fine. Let's look at another example. What if you had to make two server calls simultaneously and the state of your UI depended on both of them executing successfully? So to do such a straightforward thing, you will have to maintain three different variables and do unnecessary computation inside each of your callbacks. And this is only with the success. I have not even handled error here. So how do we manage this? Promises. The promises promises you an object, which is, it gives you as a result of a rushing computation. So you don't have to bother if that async call was completed or not. You have your promise and you can pass it around like an object inside your application. But again, if you are writing and then you will have a then function inside it, you will pass a callback for success and you will pass a callback for error. So but again, if you're writing a real world application, you have some problems, right? A promise executes only once. And as soon as it is executed, it is done with what it has to do. It is not cancelable. There is no concept of cancelling a promise once. So the promise resolves. You'll have to do something with the data. You may have to write an if condition to ignore it if you don't want it. You may have to write some complex stuff to get the latest promise out of all the, all the calls that you made. And event listeners don't have promises, right? That's a, that's a tweet from the guy who is working on RX. He says that bringing promises is like bringing a knife to a gun fight, which I think it is pretty funny. Promises is almost there. It has, it has all the functionality that is required to handle a synchrony. But there's just some little bit missing. So we'll, we'll fill this gap and look at what RxJS provides. Over the course of the next 20 minutes, I'd like to show you what constitutes this library, what is inside it, what are the APIs, what advantages should you, should you even use it and what advantages does it give you if you use it? And how can you start using it right away? It's a pretty small library. You can just include it and start using. RxJS is an offshoot of this project of reactive extensions. So long back in 2011, when dotnet was being used to create UI. So they had Microsoft face the same problems with handling a synchrony and UI callbacks and stuff. And so they wrote something called reactive extensions. This got a bit popular and there are like now reactive extensions for all these languages, Java, Python and all of them and one for JavaScript as well. So reactive extensions, that's the history. Reactive extensions provide you with an API for this entity called observables. So observables are somewhat like a data producer. You can look at them like a collection which produce data as time goes by. So if you model your asynchronous activity inside an observable, it keeps on calling your callbacks every time the activity is completed over time. So if you make a bunch of asynchronous calls, then you, so if you have a mouse click event, you get it whenever it happens. And you can manipulate this observable to do things in a more functional way. So observables actually model this data structure called streams. Streams is usually available in many functional programming, pure functional programming languages. So stream is a can be considered as an array of an infinite length. And it each value in the stream is lazily evaluated. So using this concept and observable can model all your events, your data requests, your animations, and so on and so forth. And for front end, at least these are the main things that we need to do. What reactive extensions does is basically combine two design patterns of the observer pattern and the iterator pattern. If you have read the gang of four, let's go on that definition only. So in the observer pattern, you have basically a, let me try this one. So you have basically a producer which gives out some, which makes some calls in the back end. And it gives out some data which can be consumed by multiple subscribers. So what this observer observable will do is it will call an onNext if it has good data. It will call an onError if it has some failures. And it will call, most importantly, it will call onCompleted when it has finished all the possible executions that were possible inside that observable. And also the fact that an observable gives out data one by one and you can treat it as a collection, implements the iterator pattern. So let's see how we can create an observable out of any activity that you want to do, any kind of computation that you want to do, you can embed it inside an observable. Let's see how you can do that. So you can convert a basic array into an observable using the from method. So if I say rx.observable.from of an array of strings, this whole, this whole expression gives me an observable. You can create an observable from promises themselves, from jQuery promises, say by using from promise. So here I have a search method that in which I have an ajax called to search Wikipedia with the string query that is input to it. And then it returns an observable form of that promise. You can even create your own custom observable. So rx provides you with the create method, which takes an instance of the subscriber. And if some conditions are true inside it, say your ajax called succeeded or your mouse click was done, it will call the onNext function that has to be implemented as a callback. Next, if an error occurs within this try catch, it will call your onError, just like the diagram I showed. And once it is finished all its computation, it will call the uncompleted method. An interesting part of this is that an observable.create will always return a dispose function. This effectively means that an observable encompasses its own creation and its own destruction methods. So dispose function should ideally have, should clear out any state that the observable has created within this method. So we have an API for observables. Now you need to be able to subscribe to these observables somehow. The API that rx provides is called, is a simple subscribe or you can even use for each. So if you, so in this example, I have a simple observable from an array. What this observable does is it gives me the values of each of these strings one by one. As, once I subscribe to this array, I will be receiving those values within inside this. Okay, so the subscribe function takes the, gives an onNext function and onError function and an uncompleted function. And inside each of these functions, it does whatever side effects it needs to do on that particular state of the value. So in this case, any value, there will be error. So any value that comes, go into this first function. My side effect here is a console.log. It could, it could be any HTML that I want to, I want to change or any view that I want to change. So now my output for this will be the first one, the second string, the third string and then I have, then the observable sends me a done method, a done can be logged here. So we can subscribe to the observable. So where is the functional part of it? So we have a set of combinators available in the library, which allow you to do all these and more transformations on your observable. So your, so I told you before that you can treat your observable like a collection, right? In this, on, on a normal JavaScript collection, that is an array, you can have map, filter and libraries like underscore and others provide many functions that look like this. So similarly, on your observable, you can do your map and filter, which will work in the same manner, it will map it to a new value and it will always return a new observable. Each of these will always return a new observable and not mutate the existing one. You have methods like flat map, concat map, then what else? Merge and zip, which like combine observables to form another one. You have stuff like skip, take until, reduce, throttle and stuff which change the existing observable and create a new one, which transform it, transduce it and create a new one. So we will see how to use these combinators as we go forth. So those are the four bare bones of what RXJS is. It has a concept for reactive extensions. There's a whole, so it's a tried and tested concept and it, it, there is the architecture of how streams work and all of this. There is an API to create an observable, there is a way to subscribe to the observable and there are combinators that you can use on an observable to mutate it before even subscribing to it. Let's take a deep breath. Everything is a stream. So when you're writing any RX code, remember that everything is a stream and everything comes over a period of time. And if you want to go through this again, this will be important when I show code in the future. Okay, so the second item on the agenda is that why, why do you need to even use it? Is it any good at all? Let's jump into an example where I am making a simple Ajax request using RX Observables. So here, let me open the JS. So to explain the code here, again what, what I want to do is show you that is have a set of queries. So I have this list of queries. What I want to do is for every list I want to search Wikipedia, get a search result and get a subset of that search result and somehow convert it into a string that I can, I can log here. So what do I do? I have queries. I have a set of queries which is just a list of strings. I create an observable out of these queries as my starting point. So on this observable, I flat map it over the method search Wikipedia that we defined earlier, the promise one. So what does flat map do? Flat map basically maps every, every value in this string list into the promise observable and it creates a map or it creates an array of each of the promises that come out of this and smashes them all together to form one single observable. So at the end of this, you have one single promise observable stream coming out. Now that you have promise observables here, when they resolve, they will get send a search result into this map function. So now I have the search result here and I pull out some, some subset of the result that I need. So by this time you have a stream of search results coming to you. What I do next is I zip it along with the original queries and pass it a function which will give me every value of the original query along with the associated value from the previous observable and then I concatenate the strings to form a suitable response. So what zip basically does is it combines two or more observables and then zips them together. It makes pairs out of them and provides them to this function. So all, so all my computations are done here and my subscriber has to only do the side effect of console.logging the value. Let's look if the jspin is, I can't show you how it works. Okay, moving on, do you have any questions on this? So observables give you the reactive part of coding in JavaScript. The combinators on the observables give you the functional part of doing this. So when you are, when you create an observables you're being, you are lazy evaluating. So on subscribe all this reacts immediately. Then you use your combinators which are flat maps zip and so on which are functional in their nature. So let's look at some of the combinators that we will be using. This is a visualization Rx marbles. There is a website. You can see these will be interactable on that. I tried to embed it with an iframe but it wasn't looking good. So this visualization basically shows a source stream going along here and what generated new stream out of this map. So this source stream has these values 1, 2, 3 and they map and you can map over them and in this method it is multiplying it by 10. So for every value in the source stream you will get a corresponding value here with the map applied on it. You have a delay function. This basically sets a delay on the whole stream. So the whole stream is shifted. So whatever you can actually give it a time, say I say delay by 500 milliseconds, you can shift the whole stream by 500 milliseconds and delay will maintain the differences in time between each of the values in the observable. So debounce basically waits for a certain amount of time before it says I have a value. So if I say debounce for 500 milliseconds it'll wait after a value it'll wait for 500 milliseconds give me an object. After this within 500 milliseconds it's got another value so it waits again and again until 500 milliseconds pass and it gets another value here. These methods are useful things that you do with time which if you are working on imperatively they're pretty hard to do. You'll be passing around a set of set time out, set intervals and trying to clear them at different points of time. The library provides this to you out of the box in a functional manner. So let's look at another example. So the autocomplete widget is like the Holy Grail example of RxJS. So if you see any article on Rx it'll have an autocomplete widget. Any article on streams it'll have one. So why is it so, why is it such a good example? It basically does a lot of complex stuff in very few lines of code and I feel developers, JavaScript developers would have at some point or the other implemented an autocomplete widget from scratch or at least from a library and face problems with it. So I at least did. So here what I want to do is I have a text input. On this text input for every key press I want to call for every relevant key press I want to call search wikipedia again, search wikipedia. So what all do I do to make this good experience for the user? So I have my text input. So I can use from event which is another helper that Rx provides to listen to the key up events and convert it into an observable. Now I can map over all these key up events and get the value or the text value that the user has input. This so here I get a map of all the text values that has been put into the input box. Now what I do here is so if the if the length of the string is less than two then it doesn't make sense for me to make a server call. So I'd rather filter it out. So here I have a filter which takes away any value that is of length lesser than two. So by the time you come here you have stream of strings which give you text of length greater than two. I have a debounce method here where I have debounce for 750 milliseconds. So this basically so if the user is typing really fast or pressing enter a lot of times this helps you not make those unnecessary server calls. Distinct until changed it is unless the value on the text, unless the value that is coming in this stream is a new one which is different to the previous one it will not pass it into the next method. The last one that I do is now that I have my ideal stream of text values the last thing that I do is I flat map latest over to the search wikipedia method, search wikipedia stream that I had created earlier. So what flat map latest does? We learned what flat map does. Flat map latest just ensures that you are getting the newest observable possible. So Ajax calls are finicky right? If your network is if your network speed varies you will have different Ajax calls returning at different times. So when the users type say three letters and he and you make a call and for four letters you make another call, you might get the second call before the first call. This might lead to some inconsistencies in your data, inconsistencies in your search draw in your autocomplete drop down. You don't want that and this mitigates it. So once we have our source ready we can subscribe to it and this data this subscribe on next method only needs to do the side effects that it shows whatever you need to show on your html page. Good right? Okay so yeah autocomplete is hard. I had to I struggled for a long time like I couldn't find a jQuery plugin that does exactly what I want to do and then to apply a debounce on it I had to put so many set timeouts and then clear them at every point in time. This definitely made it easier. My last example for this library is one purely on the front end. So what I want to do here is show you an implementation of mousa of your of drag and drop and show you that it is more intuitive to understand though not to write there is a learning curve but it is more intuitive to understand and it provides you with all the tail down and the creation that you need to do at every point here. So let's go through this. Say I have an element called drag target an element div whose id is that target so I pick up the jQuery instance of that. I have a mouseup event I create an observable of mouseup events. This example also kind of shows how you can compose many observables together. Then I have an observable on the mouse move event and now I start to create one on mouse down. So mouse down is the point where my drag starts. So as soon as I do a mouse down I map over the events that come out of mouse down and I basically in this map I return a stream of an off position objects which have left hand top positions. I'll do whatever computation I need here. Now I have my mouse down event ready. Now for the mouse drag event. So mouse drag stream is a combination of mouse down. Whenever a mouse down occurs you flat map over your mouse move event. Get the new positions and you stop your mouse movement, mouse move event using whenever the mouse up happens right. This is how drag works. So when you click on an object you start your drag and you want to move the object to wherever and when you click out of it you stop your movement. So this has another unique advantage that this mouse move does not get triggered unless a mouse down is triggered and a mouse up and as soon as a mouse up is done your mouse moves are disposed of. So yeah I found this harder to do when I'm writing imperatively. I have an example I can show you later. So now that I have my mouse drag mouse drag event stream ready I have I subscribe on it and all I want all I have to do is change the position of the drag target. So this is one example of how you can compose your observables together. So I have many observables working here and an example of how it takes care of creating and destroying itself. So that's pretty useful. So on our agenda we move on to how you can use this RxJS library right away. So in these examples in these previous examples I implemented them in JS bin also and all I had to do was include the Rx.all library. So if you're using a vanilla JS project a small project or something that includes jQuery or even something on the back end with NodeJS then all you have to do is include Rx.star.js I say star because there are many versions depending on what combinators you want in your application. So you have Rx.all, Rx.light and so on. So for jQuery support, special support you have Rx.jQuery. So this basically provides you with methods like on as observable here. So you just take your jQuery object and observe over whatever events you want to. Also Rx has, so once you've included this you use either of these methods to create a new observable and then once you have a new observable all you have to do is start working on it using the combinators. So what if you're using a framework right? Your mvstar framework there is good support or from Rx for your framework. So for react it basically gives some mix-ins and I'm not sure a parent component or something like that using which you can watch variables and create observables for any back-end calls. So I'm not an expert at react. You have RxEmber. RxEmber basically gives you a way to bind your components and and watch values as they come and you can create computed variables using RxEmber which basically bind every new value to the view. You have an RxAngular. So in angular the pane is dollar watch. So RxAngular what implementations I have seen take care of this creation of watch listeners and destruction of them. Other than these three there is a project called CycleJS. So what CycleJS provides you with is a framework or a structure to write all your Rx code and it also has embedded within it support for virtual DOM. So you have all your functional things going on and every side effect will be propagated through the V DOM. Some more concepts inside RxS. Yeah I told you the four but there are other more complex stuff inside it. So there is a concept of hot and cold observables. This basically allows you to decide when the observable should start giving the subscriber data. Should it give it data even if the subscription is closed and so on. There is a concept of back pressure. So back pressure is really the way we handle we handle things when an event gives you more data than you can handle. Then you can like basically handle. So in case of in case of our autocomplete we had we had a case where if the user typed really fast or if you pressed enter really fast you don't want to handle those things. So you have stuff like your throttle and debons which do back pressure for you. Also if you don't want so throttle and debons basically you lose certain events in between. So if you don't want to lose those events Rx provides you with the buffer kind of a thing where you can put things in the buffer but that too has its limitations because if the data source is limiting continuously your buffer also gets filled up. And there are some more APIs within Rx so that you can write better structured code. There is something called RxSubject and Rx schedulers and timers which allow you to do various various different things inside that. So say I had to wait after a mouse down to to determine whether it was a click or a drag event then I would use a timer to keep keep that distance. So key take away is what I want you to understand from this talk is that declarative programming is a much more better paradigm for what we do in javascript. So as the as the days goes by we have new new things coming inside we have stml5 APIs we have web workers all of these work on some kind of message passing system. It will get harder to manage as your code base grows. So writing declaratively will definitely be a win. So that means automatically you have your side effects localized to only some places. So in Rx you have your side effects localized to only the subscriber. Error handling becomes smoother. So in my autocomplete example if you wherever I would get an error that would get propagated to the subscriber directly. It is more composable you can call functions one over the other and streams streams are awesome. I feel writing this way leads to more robust code one because this are reactive extensions is a tried and tested method from a long time people have been working on it and they have also made it browser compatible all the way up to isx to have not tried it and they do work on performance though I don't have benchmarks they do work on performance and they want to be better than the other other FRP libraries out there. So what are the other FRP libraries out there? So the picking is small but it is I have not used all of these I have used bacon js I have read what is kefir js so bacon js is basically something that was inspired out of rx so the author couldn't understand couldn't trap his head around what halting cold observables are so he created two kinds of streams called event stream and properties and bacon js is basically a much friendlier library it is smaller and it is and documentation was better until up to a few months ago but it is not a very performant library so what the people at kefir js want to do is that they want to take the concept from both of these and make it a very performant library to make to write FRP FRP meaning functional reactive program then you have various other other libraries which are trying to do the same thing all these are linked in my slides I'll share them later yeah so who uses this right so the currently the people I know who use it in production are well I use it for a very small I had to write a search console and I use this for the first time that Netflix uses it extensively they are evangelists of this library and they they have open sourced library called hysterics with rx java which is being used like pretty much everywhere everywhere where people want to do simultaneous calls to aggregate data or something like asana big propagators of reactive program though I don't know if they're using rx at all so resources so after this please go try at least writing one observable in this and you can use either of these things to learn more about it you have egghead IO videos which are really good they're short videos explaining each concept in rx you have learn rx which is a so I showed you in the tweet right which is a tool by jafar hossain he's a he works at netflix so what learn rx provides you with it it provides you with a repel kind of of a webpage where as he goes on introducing concepts you have to solve problems it's it's it's really useful though very basic then this is awesome talk by him explaining what I mean it's a it should have been a precursor to this talk but now if you go watch it it'll make more sense and he explains it much better than I do that's it uh I am open to questions I hope you get distracted by that hi uh did you try uh migrating and legacy jscode to rxjs library and what was your experience if so so not a complete migration I did not help I saw a friend of mine do this for node code it doesn't really reduce the lines of code as you would expect but definitely it becomes much more reasonable so stuff like so random stuff like you were you were doing you were having a for loop with like which goes from zero to 16 and fill some data so all this stuff uh became more um what do you say functional and uh yeah adding new features to this also became a little bit easier so as time goes you will see whether other developers also find it easy yes and this library is from is it from the microsoft team the rx so microsoft originally started the reactive extensions project this library is very supported by netflix right now but it's open source thank you hi so how expensive is it to add an I can't see yeah okay so how expensive is it to add an observable to an object as opposed to adding a watch on the same object the native uh watch call native watch yeah um so what do you want to do with the native i mean so given the fact that if my side effect is pretty simple as simple as just doing a console dot log so is it uh advantages to use this so the advantage major advantage of using the library is the composability that it provides right so it basically allows you to do a lot of computation beforehand so the what i wanted to show with the j has been earlier was that uh until a subscriber comes to this none of the code in that source observable will be executed so only when a subscriber is added to it all that gets executed so you could call it lazy uh so every time there uh there is a subscriber only then it will get so this advantage i feel would be better using this library but internally it would be the same concept as a watch right yes it would be my my basically usb for this library is that it makes your code more maintainable and when you are developing something along with the large number of developers it makes it easy to communicate certain things uh and for them to for anybody to work on the code base that's what i feel my opinion thank you uh hi i'm here so very interesting library mentioned um my question is in the beginning you mentioned about problems associated with nested callbacks and rx j's uh solves this problem very elegantly so how does it solve the problem i mean is it in a way similar to uh how other libraries out there solve this very problem like async for example nested callbacks meaning you are get you are having two different data sources you want to call one inside the other so rx kind of solves it using the flat map uh method so you can combine various observables to form uh so basically nested callbacks means you have say an ajax call you get some data out of it you have another ajax call dependent on it you get some more data out of it and you in the end you want to work on the uh data of the second ajax call right so such kind of thing can be can be done by composing two different observables so you have two data sources you can compose them together and subscribe to this as a whole in the end so that is the elegant solution i was talking about and one more um so this is uh meant only for ajax calls or it could be used for any other uh blocks of code which have like this contact so the method that i showed where uh you can create an observable on your own so in that you can put uh so in this method you can basically put any any async thing that you want to do have a success callback inside it and then project it as an observable so web sockets event listeners uh your i-frame messages all of these can be put in thank you hey uh nice presentation and nice images um so my question is uh not particular to rxj's uh but um on the abstract level um so we have this observed pattern right so how does it compare with the publisher subscriber um model uh so the publisher subscriber only implements the observer pattern you don't have your iterator inside it so you don't get the uh uh what at least in my uh in the context of my talk you do not get the advantages that you do with using a stream data structure in a pubsub model basically we are seeing that this is implementation of pubsub yes yes it is a higher level uh highly abstracted implementation of that hi here okay see right so according to the reactive reactive manifesto this rx hello uh according to the reactive manifesto this rxj's covers all the fourth reactive manifesto things are you asking me uh i so reactive manifesto is a very large document uh so i don't know up to whether it uh implements it to the full extent um learning uh learning whatever in this uh also was i was new to functional programming also when i got into this so no i haven't really read the full reactive manifesto okay thanks any other questions thanks a lot for having me here folks please use your new