Javascript

What is RxJS? And Why You Should Know About It

7 min read
This article was written over 18 months ago and may contain information that is out of date. Some content may still be relevant, but please refer to official documentation for the latest information.

There are a lot of interesting tools and resources to pick and choose from in this vast world of frontend development. In an effort to curate a powerful and practical direction with my learning, I sat down with one of the most prominent figures in the RxJS community, Ben Lesh, to learn more about RxJS and why it would be a good investment of time, as a junior developer, to learn and incorporate it into my code.

He walked me through ways I can apply RxJS and tips on how to go about learning it.

Q: What is the problem that RxJS solves?

A: Coding is all about problem solving and finding the right tools to fix the right problems. In the case of RxJS, the problem being solved is the ability to handle asynchronous calls with multiple events. But what does that mean exactly?

Imagine that you are writing a function that carries data along a series of actions and there is an error. If you are just using functions to handle the series of requests, there may be some unnecessary steps that are taken to return the error. Rather than passing the error through all of the functions, it should be able to take the error and update the view without running through the now unnecessary Ajax requests.

You may note that promises are made to solve this type of error handling, but RxJS takes the concept of funneling consecutive actions to the next level. A promise can only handle a single value, limiting it use cases. Additionally, promises are not cancellable, meaning that it has the potential to block the thread and use up unnecessary resources (important consideration for resource constrained devices).

Conversely, RxJS offers a solution to these limitations by offering more than one channel of communication to simplify the handling of a multi-step event in an efficient way. RxJS also provides developers the ability to treat anything that needs to fire an event as a single shaped thing. When everything is the same shape, it becomes very easy to combine and merge and query those things resulting in a very powerful tool.

Q: Why learn RxJS?

A: On the upside, it is a powerful tool that turns complicated series of actions into concise code that is easy to manipulate. On the downside, there is a lot of language involved that requires a bit of time to learn. However, it is worth it when you realize that with one line of code, you can do something like build a drag and drop which takes three sets of events and coordinates them together (mouse down, mouse movement, mouse up) to make one concise line of code. Which would otherwise be a few dozen lines of code.

Q: What are the perks of using RxJS?

A: One of the most attractive features of integrating RxJS into your code base is that the more you use it, the more you can do with it. RxJS is analogous to using Legos in the sense that Legos are great for inventive construction because all the nobs are the same shape. Similarly, all observables take the same form so building with observables becomes an enticing proposition because you can entertain many creative solutions. The more one uses observables throughout a code base, the more options you have to build upon existing structures.

Q: What would it look like if one wanted to integrate observables into a large codebase?

A: You can use observables in pretty much any application. It might take a bit of time to adjust as a team but if you:

-Start with applications of observables that are simple and appropriate -Comment the action well -Are willing to work with your team to educate everyone on what you are doing

It should be a smooth and helpful step for your team. It might take some time for everyone to learn it on their own, but don’t be surprised if you see your team start to “Rx everything”. When actions use observables, they all take the same shape and it becomes more exciting to use as it becomes more ubiquitous throughout your app.

Q: Is it ever not a good idea to use observables?

A: Sure! If it’s a single event and it’s doing a single thing, like a lot of JavaScript programming is, then RxJS is a little silly -– you can use it, but it would be overkill.

A drag and drop is a perfect example of when you would use it. It is an event with multiple actions that call for a reduction in complexity when possible.

Q: How can you tell when you should use Observables?

A: It is helpful to qualify when to use observables by context. For example, -If your action triggering multiple events — use RxJS -If you have a lot of asynchrony and you are trying to compose it together — use RxJS -If you run into situations where you want to update something reactively — use RxJS -If you are handling huge sets of data in arrays and you need to process the sets of data in steps, you can use RxJS operators as a sort of transducer where it processes those sets of data without creating intermediate arrays that then need to be garbage collected later.

Q: Where should one start when diving into the plentiful world of Rx operators?

A: Your go-to list of operators should include map, filter, and scan. Other important operators would be: -switchMap -concat -share / shareReplay

You can narrow your use of operators to less than 10 most frequently needed operators. There are always the strange esoteric operators to play around with like pairwise, bufferCount and groupBuy. They exist for a reason, but you don’t use them very often. However, on the occasion that you do need to perform these functions, you don’t have to go through the headache of building it yourself.

Q: How easy is it to get started writing RxJS in a framework like React? A: It is very similar to implement RxJS in React as it is to implement in Angular where is has been fully adopted. In Angular, observables are first class citizens so there is a particular ease that comes with using it in Angular. However, it is as simple as subscribing to RxJS on ComponentDidMount and unsubscribing on ComponentWillUnmount. It is the same idea as when you implement in Angular if you were to implement it manually.

Q: Do you have any tips on debugging Rx?

A: Like anything, it becomes easier to debug as one learns more about it and becomes more comfortable using it. There are some situations that are difficult to debug. I’m currently working with the Chrome dev team to work out solution for these particular cases.

One common obstacle people run into is when you return something from a mergeMap and its expecting an observable, but it returns something that is not an observable, people want to be able to see the function that is returning what they thought was an observable but is not. Currently, there is no way to show that because you can’t know the form of what is being returned until after it has returned. The pro-tip for this case is to: -use a lot of console log -compose the do operator into the observable chain so that you can see where the observable is in each step and what is being returned.

Q: What is coming up in the Rx future?

A: There are a few changes to look forward to in the future of RxJS. Lettable operators will soon be introduced for public use. Instead of having operators where you have a map operator on an observable itself, you’ll be given a map function and when you call it, it returns another function that an observable will then use to do the exact same work. For example, rather than writing observable.map.filter.scan, you write observable.compose(map, filter, scan). This is a very powerful change because when you get functions building functions a lot of functional programming opportunities opens up. Another advantage associated with this change will be better tree shaking. Right now that isn’t happening with RxJS because everything is being stuck on a prototype so you can do the dot chaining. So it assumes your using it all even though you are not.

Q: How is the growing popularity of RxJS changing the landscape of React and Angular?

A: As RxJS becomes more accessible and easier to integrate, I hope it will become more ubiquitous throughout the frontend community. Currently the two biggest obstacles to using RxJS are the learning curve and the space it takes up. RxJS has been around for a long time but previously the core team found it very difficult to figure out how to get it into the hands of the programmer in an understandable way. The creators of Rx are brilliant but they use complicated terminology which has resulted in a lack of participation by the average developer. Thanks to an increased advocacy for learning resources such as This Dot, there has been a large uptick in developer adoption of this remarkable tool.

To further the ease of this adoption, I am currently working on reducing the size of the RxJS. You can look forward to news of Tiny Rx — or T-Rx which takes the 24k (g-zipped) library to just 3k!

It is very exciting to see the growing popularity and implementation of Rx across the community. While interest has increased, there is still a way to go before it becomes widely used in communities outside the valley. It will be interesting to be a part of this growth and development of such a powerful tool.

Now that you have dipped your toes into the possibilities provided by RxJS, if you are interested to learn more, check out more resources like Rx Workshop, Intro to Rx, Thinking Reactively, RxJs in Depth.

Interviewee Ben Lesh Software Engineer at Google RxJS 5+ Project Lead

Author Necoline Hubner React Apprentice at This Dot @necolinesan

Keep reading

View all posts →

State of RxJS Wrap-up

In this State of RxJS event, our panelists discussed the current state of RxJS and the upcoming features and improvements of the highly anticipated RxJS 8 release. In this wrap up, we will talk about panel discussions with RxJS core team members, which is an in depth exploration of the upcoming RxJS 8 release, highlighting its key features and performance enhancements. You can watch the full State of RxJS event on the This Dot Media YouTube Channel. Here is a complete list of the host and panelists that participated in this online event. Hosts: Tracy Lee, CEO, This Dot Labs, @ladyleet Ben Lesh, RxJs Core Team Lead, @BenLesh Panelists: Mladen Jakovljević, Frontend Web Developer, RxJS Core Team member, @jakovljeviMla Moshe Kolodny, Senior Full Stack Engineer at Netflix, Previous RxJS Lead at Google, @mkldny Marko Stanimirović, NgRx Core Team Member GDE in Angular, @MarkoStDev State of RxJS Ben kicks off the discussion by updating everyone on the current state of RxJS. He starts off by recommending those using RxJS v6 to update to the current version 7.4 because it is about half the size of v6, and he says that v8 will reduce the size even further. There are also performance updates with 7.4 where the speeds improved 30 fold. RxJS version 8 is currently in alpha! There are not as many breaking changes with this version. The major breaking change in this version is that they are removing the long deprecated APIs. They are really wanting people to try things in the alpha version, especially the 408 loops to subscribe to observables. It is an interesting way to consume observables that use the platform, and may work really well with other people’s async await usage. Operators The team is currently trying to figure out a way to show people how they develop operators by giving them the means of developing operators. They currently have a problem where they externally tell people to develop an operator with this, you subscribe, and then you give this kind of hand rolled Observer there. Internally, they have a createOperatorSubscriber which replaces the operate function. They want a reference where you can see how to develop an operator using the ones already there to build your own. There is also a plan to make sure that the RxJS library works as a utility library to work with any Observable that matches the contract. Docs Mladen gives an update of the docs for RxJS. He explains that there aren’t a lot of updates currently with the docs. He explains that there were some issues in the past with exporting operators from two places. There was also an issue with the Docs app build running in the pipeline. He explains that these issues should now be resolved, and that there hopefully won’t be any more issues there. Pull requests are always welcome when working with RxJS docs. They try to stay on top of merge requests as well. NgRx Marko talks about NgRx and RxJS. He explains that RxJS is the main engine of NgRx for almost all of the libraries, especially State Management. A few packages, like direct store, implements a Redux pattern, but uses RxJS under the hood. Pipe Moshe brings up the typings for pipe. All of RxJS’s pipe methods and functions, including the new RxJS function, will work with any unary function. General Questions One of the first questions brought up was if RxJS should not be associated with Angular anymore. Ben brings up the fact that recently, there have been a lot of React people downloading RxJS. Another question was why NgRx is switching to Signals. Marco talks about how NgRx is a group of libraries that is used in Angular. NgRx needs to be in accordance with Angular. One main reason is because of the performance improvements with the change detection strategy. There were also other questions about contributing to RxJS and coming up with a way to utilize the docs for that. There are also questions about the RxJS community, and that there currently isn’t a discord or anything like that for it right now. Conclusion The panelists were very engaged, and there was a lot of dialogue about RxJS and the future that is to come with it. The question and answer portion at the end covered some great material that all the panelists took part in answering. You can watch the full State of RxJS event on the This Dot Media Youtube Channel....

Bruce Wiggleston4 mins
RxJS

Introducing @this-dot/rxidb

When we are working on PWAs, sometimes we need to implement features that require us to store data on our user's machine. One way to do that is to use IndexedDb. Our team at This Dot has developed @this-dot/rxidb to create an RxJS wrapper around it....

Balázs Tápai6 mins
RxJSJavaScriptTypeScriptIndexedDB

What's the Latest in RxJS News? RxJS 7.5 Release Updates

Are you ready? The latest updates to RxJS 7.5 boast some exciting new features. Major highlights include changes to the the RxJS roadmap. Now RxJS will be broken down to smaller packages #6786 in order to give the team the ability to publish smaller independent RxJS packages. Through this change, for example, developers will import libraries like observables as @rxjs/observables instead of rxjs/observables. This will give library authors and developers the opportunity to only import the package required for their projects. It will encourage more community contributions to separate packages, and also reduce the build size for RxJS. Other updates for RxJS 7.5 Patch Release RxJS 7.5 is the latest release, which added a number of new features that have also improved performance metrics. New features in RxJS 7.5 retry and repeat APIs allow developers to add a delay configuration to these operators (#6640 and #6421), which simplify similar operators retryWhen and repeatWhen. With these improvements, retryWhen and repeatWhen will be deprecated and removed in coming major versions #6859. The share operator was extended to allow developers to pass an observable factory to control the reset behavior, and enable reset delays, #6169. Documentation improvements RxJS 8 has now seen an alpha release, which you can check out by reviewing the official roadmap. RxJS is moving to use NX monorepo for the doc site, and RxJS main builds #6786. Other proposals include Standalone packages like the Observables package. The Standalone Observable package will unify observables usage with the existing patterns in other libraries. This will promote adoption for the proposed native observable with TC39, for which the RxJS team has been advocating. Chrome Dev Tools The Chrome Dev Tools team is discussing whether to add debugging tooling that can help developers debug features in RxJS. Curious about more updates to RxJS? Make sure to check out the Github repo and follow the changelog for more information....

Hassan Sani2 mins
RxJSJavaScript

State of Angular Ecosystem - Updates in RxJS, NgRx, Ionic, Nx, Cypress, NgGirls, and more.

In the latest State of Angular Ecosystem, core contributors of major Angular ecosystem projects shared their thoughts on the new APIs released with Angular 14, and how the community is integrating or updating other libraries like NgRx, Nx, Ionic, and RxJS for the release. Panelists also talked about community initiatives and trainings in Angular, including NG Girls and This Is Angular. Here is a complete list of the hosts and panelists that participated in the online event. Hosts: Tracy Lee, CEO, This Dot Labs, @ladyleet Nacho Vazquez, Senior Software Engineer, This Dot Labs, @nacho devc Panelists: Ben Lesh, RxJs Core Team Lead, @BenLesh Mike Ryan, Principal Architect, LiveLoveApp & Co creator, NgRx, @MikeRyanDev Liam DeBeasi, Lead Developer, Ionic Framework, [@LiamDeBeasi] (https://twitter.com/LiamDeBeasi) Juri Strumpflohner, Director of Developer Experience at Nrwl, @juristr Jordan Powell, DX Engineer at Cypress.io, @JordanPowell88 Shmuela Jacobs, Web Development Consultant, Founder at ngGirls, @ShmuelaJ Erik Slack, SE Technical Lead at Cisco, Co Producer of NgXP.show, @erik slack Lars Gyrup Brink Nielsen, Co Founder of This is Learning, @LayZeeDK You can watch the full State of Angular Ecosystem event on This Dot Media's YouTube Channel. Libraries And Tools NgRx with Angular 14 NgRx 14 is in its beta version, and contributors are working on integrations and features, including adopting Angular 14, to highlight both the store package and the NgRx Components Package. The NgRx Store package update will include a number of features and benefits: The team is working to make it easier to implement an NgRx Store, requiring less code. A new createActionGroup() function to simplify and reduce the amount of code it takes to create a group of actions for an NgRx Store. NgRx ESLint Plugin will be added to your project automatically when you install an NgRx store to help improve code implementation best practices. NgRx Component Package NgRx Component is a project that looks toward the future of Angular by improving the process of developing Reactive components using Observable. NgRx Component is completely separate from NgRx store, and it features new improvements, including: Type checking templates More control for error handling Improved performance when you don’t have Zone.js Make sure to check out NgRx 14.0 beta ng add @ngrx/store@next. Nx with Angular 14 Nx version 14 was released three weeks ago, with a minor release (14.2) soon following. With these products, the team focused on reducing configuration for Nx to make it simple to just install Nx in a project, and start working with it immediately. Other updates include: Nx.json file is optional with this release It comes with Angular 14 out of the box It includes ng update for automatic migration to the latest Angular version It includes TypeScript 4.7 support Storybook 6.5 support and upgraded Prettier Preparation for integrating the just released Cypress 10 is on the way Nrwl Nrwl has now officially ​​taken over the stewardship of Lerna.js. Nx was always able to integrate with Lerna directly to publish features, bootstrap, and use Nx for task scheduling. It was only made official recently when the main readme was updated, but Nrwl has already maintained Lerna for a couple of years. The purpose of this is to help the Lerna community continue to evolve. The team already made some updates, released version 5 with security patch support, and deprecated some old packages. Additionally, they removed support for old Node versions, and improved the developer experience. Nrwl has a roadmap for upcoming Lerna features that you can check out. For version 5.1, the team added a very easy opt in feature for Nx which allows developers to install Nx and start using it without the need for configurations. However, this version allows developers to still have the Lerna commands with Nx as an additional package. Ionic Angular At the most recent Ionic Conf, we learned that Ionic and Angular power about 10% of Apps on the Apple App store, and 20% on the Google Play Store. Ionic 6.1 was released with a number of improvements to UI Components. Ionic is working on a Component Playground feature to be released under the Ionic docs website soon. This feature will help developers interact with the UI, see exactly what it will look like, and switch between iOS mode, Material Design mode, or Dark and Light Design modes. With Capacitor, the Ionic team announced the Native Google Map plugin, a highly requested plugin from the community. Ionic’s next release will come with Angular 14 support. Angular Girls (Ng Girls) Ng Girls is an organization that trains women on the fundamentals of Angular. As physical events return, the team is working on workflows and processes to make it easy to join or host mentoring sessions for Ng Girls. Ng Girls founder Shmuela Jacobs recently released a course that helps developers learn How to Build applications with Angular. You can check out her course to learn more. This Is Angular This Is Learning is the non profit organization behind the “This is Angular” course. All of the courses on This is Learning are free for anyone, and are also available for anyone to contribute to. Check out the website This Is Learning to learn more! Changes to Angular for Library Authors It is highly recommended that library authors who are not using IVY compilation yet migrate to the latest version before Angular compatibility support is officially removed. This removal could render such libraries unusable with new versions of Angular. The new Standalone APIs give library authors the opportunity to provide independent configuration functions that can be used without the need for Ng Modules. The independent inject function constructors and property initializers allow library authors to try out new patterns that are best suited for libraries and Angular applications. Starter.dev This Dot Labs recently released Starter.dev in beta, which offers starter kits in a variety of languages that allow developers to figure out architecture configurations. Starter.dev has a starter kit for Angular and it is available to test. Check out https://starter.dev to learn more. Other Announcements Our event concluded with the announcement of a new book called The Angular Developer's Nx Handbook by Lars Gyrup Brink Nielsen. Want to learn more about Angular? Check out the official Angular blog and head over to the This Dot blog for more Angular content!...

Hassan Sani5 mins
RxJSAngular