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.
RxJs Classes & functions
1. Observable
A representation of any set of values over any amount of time. This is the most basic building block of RxJS.
import { Observable } from 'rxjs';
const foo = new Observable(subscriber => {
console.log('Hello');
subscriber.next(42);
});
foo.subscribe(x => {
console.log(x);
});
foo.subscribe(y => {
console.log(y);
});
OUTPUT
"Hello"
42
"Hello"
42
2. BehaviorSubject
Requires an initial value and emits the current value to new subscribers
import { BehaviorSubject } from 'rxjs';
const subject = new BehaviorSubject(11);
// two new subscribers will get initial value => output: 11, 11
subject.subscribe(console.log);
subject.subscribe(console.log);
// two subscribers will get new value => output: 22, 22
subject.next(22);
// new subscriber will get latest value (22) => output: 22
subject.subscribe(console.log);
// all three subscribers will get new value => output: 33, 33, 33
subject.next(33);
// OUTPUT :: 11, 11, 22, 22, 22, 33, 33, 33
3. combineLatest
Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables.
import { combineLatest, timer } from 'rxjs';
const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
const combinedTimers = combineLatest(firstTimer, secondTimer);
combinedTimers.subscribe(value => console.log(value));
// OUTPUT Logged
// [0, 0] after 0.5s
// [1, 0] after 1s
// [1, 1] after 1.5s
// [2, 1] after 2s
Summary
In this tutorial we learnt about few important classes of RxJS and its functions.
Hope you like it !






