pairwise and partition Operator in Angular

In Angular's RxJS library, the pairwise and partition operators offer different ways to manipulate and handle streams of data from observables.

pairwise Operator

The pairwise operator groups consecutive emitted values into pairs, creating a new observable that emits arrays of two consecutive values.

Usage

import { of } from 'rxjs';
import { pairwise } from 'rxjs/operators';

// Example observable
const source$ = of(1, 2, 3, 4, 5);

// Apply the pairwise operator
const result$ = source$.pipe(pairwise());

// Subscribe to the result
result$.subscribe(value => console.log(value));

Output

[1, 2]
[2, 3]
[3, 4]
[4, 5]

In this example, the pairwise operator groups the emitted values into pairs, resulting in arrays of consecutive values.

partition Operator

The partition operator splits the source observable into two observables based on a predicate function. One observable will emit values that satisfy the predicate, and the other will emit values that do not.

Usage

import { of } from 'rxjs';
import { partition } from 'rxjs/operators';

// Example observable
const source$ = of(1, 2, 3, 4, 5);

// Apply the partition operator
const [evens$, odds$] = partition(source$, value => value % 2 === 0);

// Subscribe to the even values
evens$.subscribe(value => console.log('Even:', value));

// Subscribe to the odd values
odds$.subscribe(value => console.log('Odd:', value));

Output

Even: 2
Even: 4
Odd: 1
Odd: 3
Odd: 5

In this example, the partition operator splits the source observable into two: one that emits even numbers and another that emits odd numbers.

Key Differences

  1. pairwise

    • Groups consecutive values into pairs.
    • Useful for comparing previous and current values.
  2. partition

    • Splits the source observable into two based on a predicate.
    • Useful for separating values that meet a condition from those that don't.

Both operators enhance the ability to manage and manipulate data streams in Angular applications effectively, making it easier to handle complex reactive programming scenarios.


Similar Articles