Skip to content

Developer Insights

Join millions of viewers! Our engineers craft human-written articles solving real-world problems weekly. Enjoy fresh technical content and numerous interviews featuring modern web advancements with industry leaders and open-source authors.

Newest First
Tags:RxJS
State of RxJS Wrap-up cover image

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....

Introducing @this-dot/rxidb cover image

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....

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

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....

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

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!...

How to Contribute to RxJS cover image

How to Contribute to RxJS

This Dot Media is kicking off a brand new series of videos in 2022 to help developers learn how they can contribute code to some of the world’s most popular JavaScript frameworks and technologies. Subscribe to This Dot Media’s Youtube Channel. To continue our series, highlighting best practices for developers interested in contributing to their favorite technologies, I met up with my good friend and creator of RxJS, Ben Lesh. If you would like to check out that interview, you can see it here. What is RxJS? RxJS is a library for reactive programming that uses Observables to make it easier to compose asynchronous or callback-based code. It is a rewrite of Reactive-Extensions/RxJS with better performance, better modularity, better debuggable call stacks, all while staying mostly backwards compatible, with some breaking changes that reduce the API surface. Ben Lesh Ben Lesh is an international speaker and RxJS Core Team Member. His involvement with the framework started a few years ago, when he was asked to work on a rewrite due to his open-source experience in other projects at Netflix. What to Know Before You Get Started According to Ben, the codeofconduct.md and contributing.md documents are the best places for new developers to start. It is crucial that new contributors abide by community standards and the correct commit format, so be sure to read through! *Quick Tips!* -Everything in RxJS is written under src/internal, where you can look at all the internals of RxJS. -The commit message generates the changelog, which can be found on changelog.md. The Best Way to Get Started When I asked Ben what areas of the repository were best for new contributors, and what areas needed the most attention, he of course said: documentation. But it’s true! According to Ben, devs can simply click the “Improve Documentation” button, and do a direct commit. Presently, the team could significantly benefit from contributors interested in checking links to ensure that they are not broken, revising grammatical errors, ensuring all information is up to date, and adding edit buttons in the documentation for individual pages. However, if developers are looking for a different challenge, they can see open requests for contribution by checking out the “help wanted” tag in the issues section. *Quick Tips!* -Don’t simply submit a bunch of PRs to get on the contributors list! Focus on contributing helpful, meaningful work that will advance RxJS! -Because issues are not checked every day, you want to make sure that there is not already a PR for it, and that it hasn’t already been assigned to someone. Also, make sure to look through the PRs to ensure that the issue is not being addressed in both open and closed PRs. What About Attending Core Team Meetings? Core Team meetings typically address in-depth issues and questions related to RxJS, and are not open to the public. However, contributors can receive invitations based on their PRs and need, so if developers are interested in attending Core Team meetings, the best thing to do is create a presence in the RxJS Community! Though meetings aren’t open or recorded, community members can view the issues, and see the tag “agenda item” to see what topics will be addressed at upcoming meetings. Usually, the discussions are commented on in the issues. *Quick Tips!* -If you are interested in getting involved, but don’t want to contribute code, go out into the world and review external articles or Stack Overflow, and help in the community! -Blog posts and explanations about RxJS are also valued by the community and Core Team! Ready to Begin? You can find the RxJS repository here!...

Using Custom Async Validators in Angular Reactive Forms cover image

Using Custom Async Validators in Angular Reactive Forms

What is an AsyncValidator, and how we can use them to improve our forms....

State of Angular Ecosystem | December 2021 cover image

State of Angular Ecosystem | December 2021

This is a recap from the event State of Angular Ecosystem, you can see the full watch on State of Angular Ecosystem | Dic 2021. This event was hosted by Rob Ocel, Software Architect and Engineering Lead at This Dot. What's is new on the Angular Ecosystem? What should be expect on the upcoming releases? How Angular ecosystem looks like in the future? Also, we had this amazing panel: - Minko Gechev, Software engineer at Google, Angular Core team. - Ben Lesh, RxJS core team lead. - Mark Whitfeld, Software engineer at Stackblitz, NGXS corea team lead. - Brandon Roberts, Senior Angular Engineer, Nrwl & NgRx maintainer. - James Daniels, Developer Relations, Firebase. - Jessica Janiuk, Senior Software Engineer, Google. RxJS updates (Ben Lesh) Weeks ago was introduced RxJS 7.4, the latest version from the RxJS team, which has many features, but first of all, the bundle size compared between RxJS 6 vs RxJS 7 (if you include everything RxJS exports, included new features!) was cut by almost the half, so if you are thinking to switch between those versions, you should go ahead. Now, v7 has tons of typings fixes/updates, but now requires TypeScript 4.2+. Most of the new features included in the new version are: - Top-level exports - Multi-cast simplified - Improved retry ergonomics - Animation Frames - New tap features - AsyncIterable support That's was most of the most importants features delivered on RxJS 7.4, but there is more such as: - Ajax/fetch improvements - Supporting for aborting promises & more... Regarding in how many downloads has RxJS, the downloads has increased consideraly since RxJS 6 in 2018. Now we can 30M downloads a week, back then in 2018 they have only 10M per week. Stackblitz (Mark Whitfeld) Now Stackbliz has support for Angular v13, this was thanks to the upgrade of Stackblitz v2, which runs over web-containers. This new upgrade to Stackblitz v2, avoid to have custom-code depending on which framework you are running, making Stackblitz more agnostic from the framework (Angular, React, Vue) you are using. In fact, there is no custom-code to support any of the most used frameworks. NGXS (Mark Whitfeld) Now NGXS has support for Angular v13, with this mayor release there are up-to-date with the latest version of Angular. They are working on deliver another big features too. Angular Core (Minko Gechev, Jessica Janiuk) Ivy Ivy now its the default engine to run compilation in Angular, which lead us a huge increase of performance vs versions who runs other engines to compile Angular. With the implementation of Ivy as default, we can see a: - 90% reduction of computational resources. - -50 mins faster build for the biggest app in Google. - Improved debuggability and profiling. - More effective relation between Github issues vs Fixes, thanks to a huge effort from the Team. - New system for RFC process. What's new in Angular v13? With the recent release of Angular v13 some new features are delivered, which include: - Removal of IE11 support (no more polyfills file, yaaaay) - Modern angular package format. - Partially compiled Angular - Removed UMD bundles - ES2020 output - Adobe font inlining - Webpack 5 cache - Dinamic validator control - Better a11y What are we building next? Some of the upcoming improvements are: - Extended analysis - Simplified factory API - Advanced guides - MDC Web Standalone components Maybe some of the biggest updates which are upcoming on the next versions of Angular are Standalone components, who will run without adding to any module. This Standalone component will be bootstrapped directly into the Angular module, and the bundle will be reduced significantly. NgRx (Brandon Roberts) The most recent version of NgRx added some new features as: - Angular v13 support - RxJS 7 support - Ivy compiled libraries support - Feature creators - Improved selectors - Contributors page Nx (Brandon Roberts) The recent release of Nx, which is v13.2, also now include Angular v13 support. Also NgRx v13, and NestJS 8 support was included in the most recen version. Now, there is a RxJS 7 upgrade option for Nx. AngularFire (James Daniels) The official library from Firebase to Angular also release some of the next features: - Firebase v9 support, entirely tree-shakable support, RxJS 7 & Angular v13 support. - Firebase v8 compatibility. - Internally uses AngularFire, increased agility and less duplication. - Partial compilation, Ivy support. - Powerful new schematics In the upcoming releases for AngularFire, the team is working to improve the next items: - Documentation drive - ng deploy capabilities - More schematics on the way... - Better bundling/rehydration - Prebuilt UI components Conclusion Angular v13 bring to us so many new features, therefore the Ecosystem of Angular is updating to support this new release. Some of the most libraries used with Angular are pushing forward and taking the framework from Google to the next level. Also the Angular team, is listening to the community and making the upcoming releases more beginner-friendly such as `Standalone components. As Angular dev, we celebrate the removal of IE11 support without that, we can take advantages of most CSS features who are not supported in that browser....

How to implement drag & drop using RxJS cover image

How to implement drag & drop using RxJS

Drag & drop is one of the features that can be very useful for the end-users of our application. Additionally, it is a great example to show how RxJS can be used to handle drag-and-drop functionality with ease. Let's see how we can implement the simple dragging behavior. To follow along with all the code examples in this article, I recommend opening this Stackblitz starter example. All examples will be based on this starter project. Define drag and drop Before we start the implementation, let's consider what the drag and drop functionality consists of. It can be split into 3 phases: - drag start - drag move - drag end (drop) In a nutshell, drag start happens whenever we press mouse down on a draggable item. Following that each time we move a cursor a drag move event should be emitted. Drag move should continue, but only until we release the mouse button (mouse up event). Basic implementation You might have noticed that a few of the words above are bolded. This is because those specific words give us a clue on how we can implement the described behavior. For starters, we can see that 3 native events will be necessary to implement our feature: - mousedown - for starting the dragging - mousemove - for moving the dragged element - mouseup - for ending the dragging (dropping an element) Let's first create Observables out of those events. They will be our basic building blocks. ` We now have our base events. Now, let's create our drag event from them. ` As you can see, due to the very declarative syntax of RxJS, we were able to transform the previous definition. This is a good start, but we need a bit more information in the dragMove$ Observable so that we know how far we drag the element. For that, we can use the value emitted by dragStart$, and compare it with each value emitted by mouseMove$: ` Now, our Observable emits all necessary information for us to move the dragged element with the mouse moving. Since observables are lazy, we need to subscribe it to perform any action. ` This works well, but only if we don't move the mouse too fast. This is because our mouseMove$ and mouseUp$ events are listening on the dragged element itself. If the mouse moves too fast, the cursor can leave the dragged element, and then we will stop receiving the mousemove event. The easy solution to this is to target mouseMove$ and mouseUp$ to the document so that we receive all the mouse events even if we leave the dragged element for a moment. ` This small change will improve the dragging behavior so that we can move the cursor freely around the whole document. Before we continue, let's clean the code by extracting the logic we've created into a function. ` This way, we can easily make our code so that it allows for multiple draggable elements: ` In case you have any trouble during any of the steps, you can compare your solution with this example. Emitting custom events The above example shows that it is possible to implement a simple dragging behavior using RxJS. In real-life examples, it might be very useful to have a custom event on a draggable element so that it is easy to register your custom function to any part of the drag & drop lifecycle. It the previous example, we defined dragStart$ and dragMove$ observables. We can use those directly to start emitting mydragstart and mydragmove events on the element accordingly. I've added a my prefix to make sure I don't collide with any native event. ` As you might see in the example above, I'm putting dispatching logic into a tap function. This is an approach I recommend as this allows us to combine multiple observable streams into one and call subscribe only once: ` Now the only event missing is mydragend. This event should be emitted as the last event of the mydragmove event sequence. We can again use the RxJS operator to achieve such behavior. ` Note that because we are using the last() operator we must make sure that the stream that we apply this operator to must emit at least one value. Otherwise it will fail with Error: no elements in sequence. To achieve that we provide the initial value using startWith operator to pass the initial mouse position. This is important for the edge case of clicking and releasing the element without actually moving it. And the last step would be to emit this event alongside the others ` This concludes the implementation. We can now use those events any way we want to. ` You can find the whole implementation here, or you can play with it below: Conclusion In this article, I've shown you that you can easily implement a basic drag-and-drop behavior by using RxJS. It is a great tool for this use case as it makes managing the stream of events easier, and allows for the very declarative implementation of complex behaviors. If you are looking for more interesting examples of how you can use the drag-and-drop events with RxJS, I recommend visiting this example. In case you have any questions, you can always tweet or DM me at @ktrz. I'm always happy to help!...

Introduction to VueJS and RxJS cover image

Introduction to VueJS and RxJS

Let's start with a brief introduction. What is VueJS Vue.js is a progressive open-source front end JavaScript framework for building user interfaces, and single-page applications. What is RxJS RxJS is a library for reactive programming, and has components that enable the composition of asynchronous code. This means it takes data as streams (Observables) that can be subscribe to. Installation/Setup Following these steps, let's set-up our Vue application, and install RxJS: ` ` ` Creating an Observable To create an observable ` An observer of an observable is an object with three functions: next, error, & complete. ` Let's take a look at an example to better understand Observables. ` From the example above, we can see that “Introduction to Vuejs and Rxjs” is printed out after 2.5 seconds, and then "completed" is printed after. RxjS operators Creating an observable manually every time can make code become very lengthy and difficult to read. Therefore, RxJS has alot of useful operators. Some of the most commonly used operators are - Creation Operators - Transformation Operators - Filtering Operators - Combination Operators - Conditional Operators - Join Operators - Multicasting Operators - Error Handling Operators We would be discussing examples on Creation, Transformation, and Filtering operators in this post: Creation operators These operators make creating an observable easy for various usecase. Some examples are 'interval', 'from', and 'of'. - interval: Creates an observable that emits sequential numbers every specified interval of time. ` - from: Creates an observable from an array, promise, iterables or string ` - of: Creates an observable from a sequence of values ` Transformation operators These operators provide data transformation techniques for values passing through. An example is 'map'. For the example below, we use map to transform our array of objects ([{name: "VueJS", language: "js"}]) into an array of strings(["VueJS"]). ` Filtering Operator This operator helps in choosing and refining how and when data is obtained from an observable. An example is "Filter". For the example below, we use "filter" to obtain an array of objects where language is "js". ` Example Now that we have discussed some of the basics, lets try building a page that shows a list of frameworks. Each item of the list should be delayed before being displayed. ` Live Demo This is a codesandbox demo for you to play around with: Conclusion RxJS is really expansive, and can't be covered in just a single blog post. To learn more about RxJs, checkout the official documentation here: https://rxjs.dev/ or https://www.learnrxjs.io/. There is also a very good Vue plugin for Rxjs here. If you have any questions or run into any trouble, feel free to reach out on Twitter or Github....

Entity Management with RxJS cover image

Entity Management with RxJS

What is state? In interactive client-side applications, we may often find ourselves dealing with 'state'. Now, state can mean a different thing based on where you apply it, but the mental model I use, and apply towards state, relates to adjectives. What is an adjective? If we ask Google, we get: > An adjective is a word used to modify or describe a noun or pronoun. So, if we take that model and apply it to our applications, we can say > state describes something about our application at a certain point in time. But this isn't an article on state, what it is, or the different kinds of state you can have. However, we need to have a general understanding of what it is, so we know how we can deal with it. The act of dealing with state is called State Management, and in client-side applications, we often need to manage UI state, and have it persist to the server. UI state is one of the most common forms of state you'll manage as a front-end developer. We are talking about questions like, "is the menu open or closed? Do we have a checkmark next to our completed task?" etc ... _UI state specifically describes how our UI components look and behave from that point in time._ Strategies to Manage UI State There are plenty of amazing strategies to manage your UI state. Which strategy to use depends on your state, and the scope of that state. By scope, we mean will our entire application have access to this state (global)? Will the entire page (specific domain)? Or will just a singular component be concerned with the state, and completely hide it from the outside world (local). Today, I will show you a strategy I use to manage local UI state specifically with RxJS, and maintain state as a collection or list of things. Keep in mind that this is just one strategy! There are a ton of great options, and unfortunately, there is no one-size-fits-all solution to this complex problem. The Story Often times, when building UIs, we need to manage a list of things. We may need to add new things, read those things, update those things, and even delete those things. For example, we have a list of contacts here for our work directory. We see our contact's name and profile picture along with the ability to add and delete contacts or update the name of that existing contact. We need to reflect our changes to our user's screen, and we also need to ship these changes to the database so they are actually saved. This part is super important, and is called persisting the data. If we didn't do this part, nothing really changes outside of our browser session! A Solution Typically, when working on problems, I'd like to start with a question. What do I have? Well, in this case, we will have a list of contacts. Let's take a look ` In this example above, we are setting a class property to the result of the get function, which happens to be an Observable. This is getting us our data from the API that will be used in our template. This is how we consume it in the template: ` Here, in our component, we capture a reference to the observable property, and set it to one we can more easily use in our template. Then, we consume it by subscribing to it in the template with the async pipe. This is an important part because the async pipe does some important things for us. First, it unwraps the value from the subscription. Second, it marks the component for change detection if that Observable emits again. Lastly, it takes care of all the tear down logic for us by unsubscribing when the component is to be destroyed. This gets us a good bit of the way there, but we are still missing one critical piece. User action! Action Streams If all we are doing is taking data to show in our templates, subscribing with the async pipe and using the data in our templates is pretty standard. Some of the time, our data isnt read only, and our users will need to do something to the data. They may need to update, delete, or even add to the data. CRUD is an acronym for Create Read Update Delete and this captures some standard actions we take on data. Now, how can we perform these actions on the data we have? Lets enter in Action Streams. Action Streams are basically the act of capturing what the user is doing, and putting it into an Observable stream. Here's an example of an action stream to capture user clicks ,` Here's a great visualization tool demonstrating how observables can fire. Checkout the mouse move example that demonstrates action streams https://rxviz.com/ The point is the user does something and we create an observable from that. Now, in the examples above, we are using Observable creation functions to achieve this. For our use case, we need to do something a bit different, because we want to control our streams, and the creation of the Observable. For this case, the Subject is a perfect tool. Subjects and Observables From the docs... > Every Subject is an Observable. Given a Subject, you can subscribe to it, providing an Observer, which will start receiving values normally. > From the perspective of the Observer, > it cannot tell whether the Observable execution is coming from a plain > unicast Observable or a Subject. > Every Subject is an Observer. > It is an object with the methods next(v), error(e), and complete(). > To feed a new value to the Subject, just call next (theValue), > and it will be multicasted to the Observers registered to listen > to the Subject. So what does this mean for us? Well, it means two things. First, we can use a Subject to emit user actions. Second, and this is the most important part, we can fire off those user emissions ourselves with the next method. This is what we need for our action streams. ` Merge the Streams So now we have our data stream (remember contacts$ :Observable = this.http.get(url) ), and our action stream. Our action stream will provide commands or instructions on what to do with our data. We need to merge those two streams together, do some computation and return our new value. Thanfully RxJS has us covered. Merging streams is done with the merge creation function. ` Pretty straightforward. Now every value flowing from each Observable will flow into that merged Observable. Maintaining the State Finally! We are almost there. We have values flowing into one place, and now we just need to let the backend know about our changes, and maintain some of that nice UI state. Anytime you're working in the pipe of an Observable, and you're going to be making an HTTP request, we know we are going to need a higher-order mapping operator. For the sake of time, here are some great talks going over all of the higher order mapping operators! Why Should You Care About RxJS Higher-order Mapping Operators? | Deborah Kurata and What GroupsBy in Vegas, Stays in Vegas - Mike Ryan & Sam Julien Which operator you pick is important, and depends on the use case, but for our purposes, concatMap is a good choice. concatMap will map the value to an inner observable (our http req), subscribe to that observable, emit that value, and unsubscribe. Now, this is pretty much the case for all higher-order mapping operators, but 'concatMap' will, in the case of multiple observables, do them in the order in which they came, and will not move on to the next one until the one it is on completes. Here's our example: ` Now, after we've persisted the data back to the state, we need to maintain some state locally for our UI, and this is where we wrap it up! Scan Operator Last, but not least, we have our scan operator. Scan allows us to maintain some state of our accumulated values after performing some computation on them. Scan is alot like reduce. It takes in an accumulator function, and then returns each intermediate result in an Observable. Here's an an example. ` To tie this all together, lets recap our strategy. Lastly here's a Stackblitz for a concrete example! https://stackblitz.com/edit/simple-entity-management...

Introduction to RxJS cover image

Introduction to RxJS

RxJS is becoming more and more popular these days. It's used in a wide range of applications and frameworks have included it as part of their implementations. The library's implementation is constantly evolving and the next major version, RxJS 7, is close to being released. What is RxJS? RxJS is a popular library with more than 20 Million downloads per week on average. According to the official website: > RxJS is a library for composing asynchronous and event-based programs by using observable sequences... However, there's another popular definition of this library: > _Think of RxJS as Lodash for events._ The original implementation was based on JavaScript (Reactive Programming library for JavaScript = RxJS). The TypeScript support It's interesting to know that the RxJS project is using TypeScript actively and it helped to find bugs when the library was migrating from JavaScript. In the next section, you can find more articles to learn and keep improving your skills through RxJS. More about RxJS The This Dot Blog has been publishing several articles around RxJS lately. Find a list of useful resources below to keep up-to-date with this technology: * Getting Started with RxJS * RxJS 7 and Beyond: What to Expect and Prepare For * Basic RxJS Operators and How to Use Them * Form Handling using RxJS and TypeScript * [Understanding switchMap and forkJoin operators in RxJS with TypeScript ](https://labs.thisdot.co/blog/understanding-switchmap-and-forkjoin-operators-in-rxjs-with-typescript) * [Form Validation using RxJS and TypeScript ](https://labs.thisdot.co/blog/form-validation-using-rxjs-and-typescript) * Best Practices for Managing RxJS Subscriptions * Understanding flatMap, mergeMap and toArray operators in RxJS with TypeScript * Going Reactive with RxJS * Mapping Returned HTTP Data with RxJS...

Mapping Returned HTTP Data with RxJS cover image

Mapping Returned HTTP Data with RxJS

Some backends either send too much data or not enough data back. When we combine what we know already about Reactive Programming and RxJS we can handle these situations in a very elegant manner using some useful operators that RxJS provides us....

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co