In this post we will talk about new features and improvements of the latest version of RxJS 6.5.0 .
RxJS now provides native support for the native fetch API, including the ability to interrupt requests with 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() { ... } });
I liked that the most. The forkJoin operator now accepts a dictionary of sources:
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 of forkJoin(a, b, c, d)
considered obsolete, 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();
The existing partition
statement is now considered obsolete, and in its place comes the new generator observable partition
statement.
Partition divides the source object into two observable objects, one for values that satisfy a given predicate, and the second for values that do not.
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') } });
The new version no longer uses the combineLatest
signatures, except for combineLatest([a, b, c])
. About the reasons for this change, read here .
Use the scheduled
statement to configure the scheduler for an existing observable. Planned (those that take the scheduler as a parameter) versions of the operators from
, range
and others are 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)
Our team creates a cool TestMace tool - a powerful IDE for working with APIs. Create scripts, test endpoints and use all the power of advanced autocompletion and syntax highlighting. Write to us! We are here: Telegram , Slack , Facebook , Vk
Source: https://habr.com/ru/post/450718/
All Articles