Using RxJS for State and Data Streams

Tutorial 2 of 5

Tutorial: Using RxJS for State and Data Streams

1. Introduction

Brief explanation of the tutorial's goal

In this tutorial, we will explore how to use Reactive Extensions for JavaScript (RxJS) in Angular for managing state and handling data streams.

What the user will learn

You will learn about Observables, a key component of RxJS, and how to use them to manage asynchronous data streams. This will include creating, subscribing to, and manipulating Observables.

Prerequisites (if any)

  • Basic knowledge of JavaScript and Angular
  • Familiarity with TypeScript and ES6 will be helpful but not necessary

2. Step-by-Step Guide

Observables

  • Observables are a new type of collection that can arrive over time. They are lazy, meaning they are not executed until we subscribe to them.
  • Observables can be created using the Observable.create() or new Observable() methods.
  • Observables can emit three types of values:
  • Next: Sends a value such as Number, String, Object, etc. It can be called multiple times.
  • Error: Sends a JavaScript error or exception.
  • Complete: Does not send a value.

Here's a basic example of creating and subscribing to an Observable:

import { Observable } from 'rxjs';

let observable = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.next('World');
  subscriber.complete();
});

observable.subscribe(
  value => console.log(value),
  err => {},
  () => console.log('This is the end')
);

In the above example, we first import the Observable from 'rxjs'. We then create an Observable that emits 'Hello', 'World', and then completes. We subscribe to this Observable and log each value to the console.

Operators

  • Operators are pure functions that enable a powerful way to handle asynchronous events.
  • Some commonly used operators include map(), filter(), concat(), and mergeMap().

Here's an example of using the map() operator:

import { from } from 'rxjs';
import { map } from 'rxjs/operators';

let numbers = from([1, 2, 3, 4, 5]);
let doubleNumbers = numbers.pipe(map(value => value * 2));
doubleNumbers.subscribe(value => console.log(value));

In the above example, we first create an Observable from an array of numbers. We then use the pipe() function to chain operators, in this case, the map() operator is used to double the value of each number. Finally, we subscribe to the Observable and log each value to the console.

3. Code Examples

Example 1: Creating and subscribing to an Observable

import { Observable } from 'rxjs';

// Create an Observable that will start listening to data when subscribed to.
let observable = new Observable(subscriber => {
  // Emit a single string value
  subscriber.next('Hello');
  // Emit another value
  subscriber.next('World');
  // Complete the observable stream
  subscriber.complete();
});

// Subscribe to the observable
observable.subscribe(
  value => console.log(value), // Handle the data within the stream
  err => {}, // Handle error
  () => console.log('This is the end') // Handle completion
);

In this example, you should see 'Hello', 'World', and 'This is the end' logged to your console.

Example 2: Using Operators

import { from } from 'rxjs';
import { map } from 'rxjs/operators';

// Create an observable from an array
let numbers = from([1, 2, 3, 4, 5]);
// Use the map operator to manipulate the data
let doubleNumbers = numbers.pipe(map(value => value * 2));
// Subscribe to the observable
doubleNumbers.subscribe(value => console.log(value));

In this example, you should see the numbers 2, 4, 6, 8, and 10 logged to your console.

4. Summary

We've covered the basics of using RxJS for state management and data streams in Angular. We've learned about Observables and Operators, and how to use them to handle asynchronous data streams.

Next steps for learning

Continue practicing with Observables and Operators. Try creating your own Observables and manipulating them with different Operators.

Additional resources

5. Practice Exercises

Exercise 1: Create an Observable that emits the numbers 1 through 5.

import { of } from 'rxjs';

let numbers = of(1, 2, 3, 4, 5);
numbers.subscribe(value => console.log(value));

Exercise 2: Use the filter() operator to emit only even numbers.

import { from } from 'rxjs';
import { filter } from 'rxjs/operators';

let numbers = from([1, 2, 3, 4, 5]);
let evenNumbers = numbers.pipe(filter(value => value % 2 === 0));
evenNumbers.subscribe(value => console.log(value));

Exercise 3: Create an Observable that emits a value every second.

import { interval } from 'rxjs';

let seconds = interval(1000);
seconds.subscribe(value => console.log(value));

In this exercise, you should see a new number logged to your console every second.