Terminology
"In computing, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change"
"Reactive programming is programming with asynchronous data streams."
import { fromEvent } from 'rxjs';
const button = document.querySelector('.button');
const click$ = fromEvent(button, 'click');
click$.subscribe(console.log); // log whole click event
import { interval, from, of } from 'rxjs';
const source$ = interval(1000);
const array$ = from([1,2,3,4,5]);
const promise$ = from(fetch('/foo.json'));
const vars$ = of('Chris', 'Stefan', 'Patrick');
const { filter, map } from 'rxjs/operators';
source$
.pipe(
filter(value => value % 2 === 0),
map(value => x + x),
)
.subscribe(console.log)
import { from } from 'rxjs';
const { switchMap } from 'rxjs/operators';
source$
.pipe(
switchMap((url) => from(fetch(url))),
);
// cancel inner observable on each new emission
const { concat, merge } from 'rxjs/operators';
source$.pipe(concat(source2$));
// append second stream after first completed
source$.pipe(merge(source2$));
// emit every event from both streams
merge(source$, source2$); // also static
import { from } from 'rxjs';
const { forkJoin } from 'rxjs/operators';
source$
.pipe(
forkJoin(
from(fetch('/api/first')),
from(fetch('/api/second')),
),
);
// emit after all observables completed
// emit final observable result
import { from, of } from 'rxjs';
source$
.pipe(
catchError(error => {
console.error(error);
return of([]);
})
);
// must return new Observable so operators
// down the stream won't fail