Search⌘ K
AI Features

The pipe and map Functions

Explore how to use RxJS pipe and map functions to transform values emitted by Observables in TypeScript. Understand combining multiple operators for data streams and the benefits of explicit typing for readability and error prevention.

Overview of the pipe and map functions

The RxJS library provides a pipe function to all Observables, similar to the subscribe function. This pipe function takes a variable number of functions as parameters and will execute these functions on each value that is emitted by the Observable.

The functions that are provided to the pipe function are generally known as Observable operators, which all accept an Observable as input, and return an Observable as output. The pipe function emits an Observable stream.

This concept is best explained by reading some code, as in the following example:

C++
// Importing the 'map' operator from the 'rxjs' library
import { map } from "rxjs/operators";
// Creating an observable 'emitter' that emits the values 1, 2, 3, and 4
const emitter = of(1, 2, 3, 4);
// Creating a new observable 'modulus' by applying the 'map' operator to the 'emitter' observable
// The 'map' operator takes each emitted value, logs it to the console, and returns the modulus of that value and 2
const modulus = emitter.pipe(
map((value: number) => {
console.log(`received : ${value}`);
return value % 2;
})
);
// Subscribing to the 'modulus' observable to receive its emitted values
// When each value is emitted, it is logged to the console with a message indicating that it is a modulus value
modulus.subscribe((value: number) => {
console.log(`modulus : ${value}`);
});
  • We start with an Observable named emitter on line 5, which will emit the values 1 through 4. ...