...

/

The pipe and map Functions

The pipe and map Functions

Learn how to use the pipe and map functions of the RxJS library to modify and combine Observables.

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:

Press + to interact
// 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. ...