RXJS Crash Course

Jul 4, 2024

RXJS Crash Course

Overview

  • Purpose: To explain what RXJS is and how to use it in applications.
  • Definition: RXJS is a library for reactive programming using observables.
  • Challenge: Conceptually difficult due to many terminologies like observables, operators, observers, pipes, unicast, multicast, etc.

Hypothetical Example: Burger Shop

  • Business Model: Customers bring ingredients (excluding buns), and you make a burger for them.
  • Supported Ingredients: Meat (only chicken, lamb, or beef), cheese, and vegetables.
  • Assembly Line:
    • Step 1: Chef 1 removes ingredients from the bag.
    • Step 2: Chef 2 checks the meat type.
    • Step 3: Chef 3 cooks the meat.
    • Step 4: Chef 4 assembles the burger.
    • Step 5: Clerk gives the burger to the customer.
  • Error Handling: If unsupported meat is provided, the process stops and the clerk informs the customer.

Relating to RXJS

  • Observable: Emitting a value (like the customer's bag of ingredients).
  • Operators: Processing and transforming the data through a pipeline (like the assembly line of chefs).
  • Observer (Subscriber): Takes the final data and does something with it or handles errors/completion.
  • Pipes: Chains of operators.
  • Marble Diagrams: Visual representations of the flow and transformations of data over time.

Coding Example

  • Goal: Build an RXJS system to calculate the average age of active users from a data set, and throw an error if the average age is below 18.
  • Setup:
    • Create a Node.js project.
    • Install RXJS: npm install rxjs.
    • Create an index.js file.
    • Import RXJS: const { Observable, of } = require('rxjs');.
  • Creating an Observable:
    • Define an observable that emits data: const observable = new Observable(subscriber => { subscriber.next(users); });
  • Creating an Observer:
    • Define an observer with next, error, and complete methods.
    • Connect the observer to the observable using observable.subscribe(observer);
  • Using Pipes and Operators:
    • Use pipe to manipulate and transform data through various operators like map, filter, and reduce.

Example Code Walkthrough

  1. Extracting Data: Use pluck to extract array of users from the object.
    const { pluck } = require('rxjs/operators');
    observable.pipe(
      pluck('data')
    )
    .subscribe(observer);
    
  2. Filtering Active Users: Use filter to keep only active users.
    const { filter } = require('rxjs/operators');
    observable.pipe(
      pluck('data'),
      filter(user => user.status === 'active')
    )
    .subscribe(observer);
    
  3. Calculating Average Age: Use reduce to calculate average age and possibly throw an error if below 18.
    const { reduce } = require('rxjs/operators');
    observable.pipe(
      pluck('data'),
      filter(user => user.status === 'active'),
      reduce((acc, user) => acc + user.age, 0)
    )
    .subscribe(observer);
    

Important Points

  • Observables emit data and can do so multiple times.
  • Operators in pipes transform, filter, and manipulate data.
  • Observers handle the final output and errors.
  • Error Handling: An error in the pipeline stops further data processing.
  • Multiple Emissions: An observable can emit several pieces of data over time.
  • Complete Notification: When complete, emissions stop and it's handled by the observer's complete method.
  • Use Case: Practical example of calculating the average age and handling errors using RXJS in Node.js.

Resources

Closing

  • This crash course provides a foundational understanding of RXJS, its key concepts, and practical application. For detailed learning, refer to the official documentation and additional resources.