Angular – RxJS Operators

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

RxJS provides an implementation of the Observable type, The library also provides utility functions for creating and working with observables.

 These utility functions can be used for:

  • Converting existing code for async operations into observables
  • Iterating through the values in a stream
  • Mapping values to different types
  • Filtering streams
  • Composing multiple streams

RxJS Operators

1. of() – Emit variable amount of values in a sequence and then emits a complete notification.

import { of } from 'rxjs';
//emits any number of provided values in sequence
const source = of(1, 2, 3, 4, 5);
//output: 1,2,3,4,5
const subscribe = source.subscribe(val => console.log(val));

2. Tap() – Transparently perform actions, such as logging.

import { of } from 'rxjs';
import { tap, map } from 'rxjs/operators';

const source = of(1, 2, 3, 4, 5);
// transparently log values from source with 'tap'
const example = source.pipe(
  tap(val => console.log(`BEFORE MAP: ${val}`)),
  map(val => val + 10),
  tap(val => console.log(`AFTER MAP: ${val}`))
);

//'tap' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

OUTPUT

BEFORE MAP: 1
AFTER MAP: 11
11
BEFORE MAP: 2
AFTER MAP: 12
12
BEFORE MAP: 3
AFTER MAP: 13
13

3. map() – Apply projection with each value from source.

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

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10));
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));

OUTPUT

11
12
13
14
15

4. debounceTime() – Discard emitted values that take less than the specified time between output.

import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';

// elem ref
const searchBox = document.getElementById('search');

// streams
const keyup$ = fromEvent(searchBox, 'keyup');

// wait .5s between keyups to emit current value
keyup$
  .pipe(
    map((i: any) => i.currentTarget.value),
    debounceTime(500)
  )
  .subscribe(console.log);

OUTPUT – On every keyup press, it waits for 500 milisec to log in console and discards the button press in between.

Note :- that in the call stack, it’s Observable.subscribe that kicks everything off. Because observables tend to be lazy, no data will flow through the pipe and map until we subscribe to the observable.

5. startWith() – Returns an Observable that emits the items you specify as arguments before it begins to emit items emitted by the source Observable.

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

of(1,2,3)
  .pipe(startWith("first", "second"))
  .subscribe(x => console.log(x));

// OUTPUT ::
//   "first"
//   "second"
//   1
//   2
//   3

6. distinctUntilChanged() – Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.

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

of(1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(
    distinctUntilChanged(),
  )
  .subscribe(x => console.log(x)); // OUTPUT : 1, 2, 1, 2, 3, 4

7. takeUntil() – Emits the values emitted by the source Observable until a notifier Observable emits a value.

import { fromEvent, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

const source1 = interval(1000);
const clicks = fromEvent(document, 'click');
const result = source1.pipe(takeUntil(clicks));
result.subscribe(x => console.log(x));

// OUTPUT:
// It will keep on logging in console number like 0, 1, 2, 3 and so on 
// until a mouse click is seen.

Pipe()

Unlike tap,map, which are operators, pipe is a method on Observable which is used for composing operators. pipe was introduced to RxJS in v5.5.

Example :

converting this

of(1,2,3).map(x => x + 1).filter(x => x > 2);

into this

of(1,2,3).pipe(
  map(x => x + 1),
  filter(x => x > 2)
);

Summary

In this tutorial we learnt one of the most important topics in RxJS, we learnt RxJs Operators , its usage with examples.
Hope you liked it !


Leave a Comment