
What's New in RxJS v6.5
- Transfer
In this post we will talk about new features and improvements of the latest version of RxJS 6.5.0 .
New fromFetch statement
RxJS now provides native support for the native fetch API, including the ability to interrupt requests using the AbortController .
import { of } from 'rxjs';
import { switchMap, catchError } from 'rxjs/operators';
import { fromFetch } from 'rxjs/fetch';
const users$ = fromFetch('https://reqres.in/api/users').pipe(
switchMap(response => {
if (response.ok) {
return response.json();
} else {
return of({ error: true, message: `Error ${response.status}` });
}
}),
catchError((error) => of({ error: true, message: error.message }))
);
users$.subscribe({ next(data) { ... }, complete() { ... } });
Enhanced forkJoin statement
I liked it the most. The forkJoin statement now accepts a source dictionary:
import { forkJoin, timer } from 'rxjs';
import { take, mapTo } from 'rxjs/operators';
const source = forkJoin({
todos: timer(500).pipe(mapTo([{ title: 'RxJS'}])),
user: timer(500).pipe(mapTo({ id: 1 }))
});
source.subscribe({
next({ todos, user }) { }
});
In addition, the use of this operator in the form forkJoin(a, b, c, d)
is deprecated, instead you need to write forkJoin([a, b, c, d])
.
// DEPRECATED
forkJoin(of(1), of(2)).subscribe();
// use an array instead
forkJoin([of(1), of(2)]).subscribe();
Partition observable
The existing operator is partition
now considered obsolete, and in its place comes a new generating observable-operator partition
.
Partition divides the source object into two objects of type observable, one for values that satisfy a given predicate, and the second for values that don't.
import { fromEvent, partition } from 'rxjs';
const clicks$ = fromEvent(document, 'click');
const [clicksOnH1$, clicksElsewhere$] =
partition(clicks$, event => event.target.tagName === 'H1');
clicksOnH1$.subscribe({
next() { console.log('clicked on h1') }
});
clicksElsewhere$
.subscribe({
next() {
console.log('Other clicked')
}
});
combineLatest transferred to deprecated status
The new version no longer uses signatures combineLatest
, with the exception of combineLatest([a, b, c])
. Read the reasons for this change here .
Planners
Use the operator scheduled
to configure the scheduler for an existing observable. Planned (those that take as a parameter scheduler) version operators from
, range
and other deprecated.
import { of, scheduled, asapScheduler } from 'rxjs';
console.log(1);
// DEPRECATED
// of(2, asapScheduler).subscribe({
// next(value) {
// console.log(value);
// }
// });
scheduled(of(2), asapScheduler).subscribe({
next(value) {
console.log(value);
}
});
console.log(3)