Top 6 Mistakes Developers Make in RxJS Code

Jul 11, 2024

Top 6 Mistakes Developers Make in RxJS Code

Introduction

  • Presenter: Dmytro Mezhenskyi
  • Target audience: Beginners with Angular
  • Goal: To help you become an advanced Angular developer
  • Application: User search component

Demo Application Overview

  • Functionality: Find users by typing names, display results, control number of results per page
  • Implementation: Reactive form with text input and dropdown, uses HTTP calls for search
  • Observable Chain:
    • Observable searchConfig$ from form value changes
    • Subscribes to searchConfig$, calls findUsers() with config
    • Subscribes to returned observable, assigns data to a class property

Mistake 1: Nested Subscriptions

  • Problem: Messy, loses reactive context, prone to errors
  • Solution: Use RxJS flattening operators like switchMap() to keep data in a reactive context
  • Benefits: Cleaner, safer, more predictable code, automatic cancellation of pending calls if new data arrives

Mistake 2: Improper Usage of takeUntil() or takeUntilDestroyed()

  • Problem: False confidence in preventing memory leaks; limited to operators before takeUntil()
  • Solution: Move takeUntil() to the end of the operator chain, use ESLint rules to enforce

Mistake 3: Manual Subscriptions in Components

  • Disclaimer: Manual subscriptions can be necessary sometimes
  • Problem: Manual subscriptions in components are not optimal
  • Solution: Use alternative methods like signals or async pipe for auto-subscription and auto-unsubscription
  • Benefits: Simplifies code, reduces risk of memory leaks

Mistake 4: Executing Observable Logic More Than Needed

  • Problem: Multiple subscriptions to the same observable cause duplicate executions (e.g., duplicate HTTP calls)
  • Solution: Use operators like share() or shareReplay() to make observables hot and share latest values with new subscribers

Mistake 5: Improper Usage of distinctUntilChanged()

  • Problem: Doesn't work properly with non-primitive data types
  • Solution: Use a predicate function for accurate comparison of objects
  • Benefit: Prevents unnecessary HTTP calls

Mistake 6: Performing Side Effects in the Wrong Place

  • Problem: Harder to understand, test, and debug code due to hidden side effects
  • Solution: Use tap() operator for side effects to make them explicitly clear

Conclusion

  • Goals: Improve code quality in Angular projects
  • Audience Interaction: Comment your top RxJS mistakes
  • Support: Share video and check out Advanced Angular video courses