RxJS Cookbook for Reactive Programming (eBook)
318 Seiten
Packt Publishing (Verlag)
978-1-78862-531-9 (ISBN)
Building modern web applications that are responsive and resilient is essential in this rapidly evolving digital world. Imagine effortlessly managing complex data streams and creating seamless user experiences-this book helps you do just that by adopting RxJS to boost your development skills and transform your approach to reactive programming.
Written by a seasoned software engineer and consultant with a decade of industry experience, this book equips you to harness the power of RxJS techniques, patterns, and operators tailored for real-world scenarios. Each chapter is filled with practical recipes designed to tackle a variety of challenges, from managing side effects and ensuring error resiliency in client applications to developing real-time chat applications and event-driven microservices. You'll learn how to integrate RxJS with popular frameworks, such as Angular and NestJS, gaining insights into modern web development practices that enhance performance and interactivity.
By the end of this book, you'll have mastered reactive programming principles, the RxJS library, and working with Observables, while crafting code that reacts to changes in data and events in a declarative and asynchronous way.
Build scalable, efficient applications with seamless async data handling and blazing-fast user experience by unleashing reactive programming with AngularKey FeaturesMaster RxJS observables, operators, and subjects to improve your reactive programming skillsExplore advanced concepts like error handling, state management, PWA, real-time, and event-driven systemsEnhance reactive skills with modern web programming techniques, best practices, and real-world examplesPurchase of the print or Kindle book includes a free PDF eBookBook DescriptionBuilding modern web applications that are responsive and resilient is essential in this rapidly evolving digital world. Imagine effortlessly managing complex data streams and creating seamless user experiences-this book helps you do just that by adopting RxJS to boost your development skills and transform your approach to reactive programming. Written by a seasoned software engineer and consultant with a decade of industry experience, this book equips you to harness the power of RxJS techniques, patterns, and operators tailored for real-world scenarios. Each chapter is filled with practical recipes designed to tackle a variety of challenges, from managing side effects and ensuring error resiliency in client applications to developing real-time chat applications and event-driven microservices. You ll learn how to integrate RxJS with popular frameworks, such as Angular and NestJS, gaining insights into modern web development practices that enhance performance and interactivity. By the end of this book, you ll have mastered reactive programming principles, the RxJS library, and working with Observables, while crafting code that reacts to changes in data and events in a declarative and asynchronous way.What you will learnManage error handling, side effects, and event orchestration in your Angular and NestJS applicationsUse RxJS to build stunning, interactive user interfaces with AngularApply Angular testing strategies to ensure the reliability of your RxJS-powered applicationsOptimize the performance of RxJS streamsEnhance progressive web app experiences with RxJS and AngularApply RxJS principles to build state management in AngularCraft reactive and event-driven microservices in NestJSWho this book is forThis book is ideal for intermediate-to-advanced JavaScript developers who want to adopt reactive programming principles using RxJS. Whether you re working with Angular or NestJS, you ll find recipes and real-world examples that help you leverage RxJS for managing asynchronous operations and reactive data flows across both your frontend and backend.]]>
1
Handling Errors and Side Effects in RxJS
Welcome to the RxJS Cookbook for Reactive Programming!
After working with RxJS for a while, and learning all about every operator in RxJS docs, have you ever felt stuck or didn’t know how to get your RxJS game to the next level? This book is Packt(ed) with advanced recipes and practical use cases to take you to that next level and make you ready for any real-life challenge in the web development world. Buckle up, it’s going to be a fun ride!
This chapter explores techniques to manage the inevitable complexities of real-world reactive programming. We’ll learn how to gracefully handle errors and maintain stream integrity. We will delve into side effect management to perform tasks such as logging, API calls, and DOM updates without disrupting data flows. Also, we will master strategies to isolate side effects and ensure predictable, testable RxJS code. Finally, we will understand the role of WebSockets as side effects and explore heartbeat techniques to ensure connection integrity in a Reactive way.
In this chapter, we will cover the following recipes:
- Handling DOM updates
- Handling network requests
- Handling network errors
- Debugging RxJS streams
- Understanding HTTP polling
- Handling WebSocket connections
Free Benefits with Your BookYour purchase includes a free PDF copy of this book along with other exclusive benefits. Check the Free Benefits with Your Book section in the Preface to unlock them instantly and maximize your learning experience. |
Technical requirements
To follow along in this chapter, you’ll need the following:
- Angular v19+
- RxJS v7
- Node.js v22+
- npm v11+ or pnpm v10+
The code for recipes in this chapter is placed in the GitHub repository:
https://github.com/PacktPublishing/RxJS-Cookbook-for-Reactive-Programming/tree/main/Chapter01
Handling DOM updates
Due to its declarative and reactive nature, RxJS provides a way to efficiently take care of DOM updates and react to UI updates without directly manipulating DOM elements.
How to do it…
In this example, we will build a small cooking recipe app, where we will load a list of recipes from the mocked BE (using MSW) and show them in the list. After that, we will implement two search fields to find desired recipes by name and ingredient. We will do this by handling input updates from both filters in a declarative way, then combining the query results and providing filtered results in the end.
Here’s how the app would look in its initial state:
Figure 1.1: Recipe app – initial state
Step 1 – Handling one search input
Let’s start easy by implementing search by name filter first. In our Angular component, we will have a searchNameInput DOM element reference and a fromEvent operator:
@ViewChild('searchNameInput') searchNameInputElement!: ElementRef; ngAfterViewInit() { fromEvent<InputEvent>( this.searchNameInputElement.nativeElement,'input') .pipe( map((searchInput: InputEvent) => (searchInput.target as HTMLInputElement) .value), startWith(''), debounceTime(500), distinctUntilChanged(), switchMap((searchName: string) => this.recipesService.searchRecipes$(searchName))) .subscribe((recipes) => this.recipes = recipes); } Here’s a breakdown of what we are doing:
- With the
mapoperator, we will extract the value of the input and state that the starting value should be an empty string with thestartWithoperator. - To prevent sending unnecessary requests and increasing load on the server, we will debounce every user keystroke up to 500 milliseconds. Also, we will check whether the search query has changed from the previous one (e.g., if we wanted to search for lasagna, we would type the query
"lasag", get the result, and then delete “g" and put “g" back in the query within 500 milliseconds; we won’t send another request, because the query hasn’t changed). - In the end, once we get the search query, we will use
switchMapto take the query value and send the request to the BE API.
Why switchMap?
The main reason we are using switchMap here is the cancellation effect. This is what it means. Assume that a user types a search query, and we have an ongoing request. Now, if the user changes the query to a new one, the previous request will be cancelled automatically, since we are no longer interested in the previous result.
Now, when we type a search query for recipes, we might see the results in the UI:
Figure 1.2: Search recipe by name
Step 2 – Handling two search inputs
Now let’s add a second search input for ingredients. Again, we will create a stream of search input events from the second input, but this time, we want to combine results with the first input as well. The way we can achieve that is by using the combineLatest function that will create a stream of events from multiple sources.
Here the startWith operator comes in handy as well, since combineLatest won’t emit any values until both inputs emit at least once. That would mean that we would see the empty recipes list initially without using startWith. This is what our code looks like after adding the second input:
const searchNameInputValue$ = fromEvent<InputEvent>( this.searchNameInputElement.nativeElement, 'input') .pipe( map((searchInput: InputEvent) => (searchInput.target as HTMLInputElement) .value), startWith('') ); const searchIngredientInputValue$ = fromEvent<InputEvent>( this.searchIngredientInputElement.nativeElement, 'input') .pipe( map((searchInput: InputEvent) => (searchInput.target as HTMLInputElement) .value), startWith('') ); combineLatest({ searchName: searchNameInputValue$, searchIngredient: searchIngredientInputValue$ }) .pipe(debounceTime(500), distinctUntilChanged( (prev, curr) => prev.searchName === curr.searchName && prev.searchIngredient === curr.searchIngredient), switchMap(({ searchName, searchIngredient }) => this.recipesService.searchRecipes$( searchName, searchIngredient))) .subscribe((recipes) => this.recipes = recipes); Notice one more important change from the previous example with distinctUntilChange. One of the most common mistakes when using operator is assuming it does figure out on its own when the stream has changed, but that only works for primitive values coming out of a stream as a result. Previously, we emitted string values from the first search input, but now since we are combining the results of two search inputs, we have a stream of object values. Therefore, we must do a deep check on previous and current object properties, in our case, searchName and searchIngredient. Alternatively, we could use the distinctUntilKeyChanged operator.
If we open our app in the browser, now we can search recipes not only by name but also by ingredient:
Figure 1.3: Search recipe by name and ingredient
See also
- MSW: https://mswjs.io/
fromEventoperator: https://rxjs.dev/api/index/function/fromEventmap: https://rxjs.dev/api/operators/mapstartWithoperator: https://rxjs.dev/api/operators/startWith ...
| Erscheint lt. Verlag | 28.3.2025 |
|---|---|
| Vorwort | Santosh Yadav |
| Sprache | englisch |
| Themenwelt | Mathematik / Informatik ► Informatik ► Web / Internet |
| ISBN-10 | 1-78862-531-5 / 1788625315 |
| ISBN-13 | 978-1-78862-531-9 / 9781788625319 |
| Informationen gemäß Produktsicherheitsverordnung (GPSR) | |
| Haben Sie eine Frage zum Produkt? |
Digital Rights Management: ohne DRM
Dieses eBook enthält kein DRM oder Kopierschutz. Eine Weitergabe an Dritte ist jedoch rechtlich nicht zulässig, weil Sie beim Kauf nur die Rechte an der persönlichen Nutzung erwerben.
Dateiformat: EPUB (Electronic Publication)
EPUB ist ein offener Standard für eBooks und eignet sich besonders zur Darstellung von Belletristik und Sachbüchern. Der Fließtext wird dynamisch an die Display- und Schriftgröße angepasst. Auch für mobile Lesegeräte ist EPUB daher gut geeignet.
Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen dafür die kostenlose Software Adobe Digital Editions.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen dafür eine kostenlose App.
Geräteliste und zusätzliche Hinweise
Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.
aus dem Bereich