翻译自原文:netbasal.com/whats-new-i…react
RxJS 已于上月2019.4.23发布。 来看下带来了哪些新功能git
基于原生的 fetch API,RxJS 进行了封装并提供了 fromFetch 方法,也就是利用原生的fetch发http请求并返回为Observable 类型。并且还支持经过基于原生的FetchController 实现取消发送中的请求。github
在线例子:stackblitz.com/edit/fromfe…json
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() { ... } });
复制代码
forkJoin 相似 promise.all() 用于同时处理多个 Observable 在v6.5中能够支持传入对象类型了api
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 }) { }
});
复制代码
此外,再也不支持 forkJoin(a, b, c, d) 形式,建议传入数组,如 forkJoin([a, b, c, d])。 译者注: 加强了可读性数组
// DEPRECATED
forkJoin(of(1), of(2)).subscribe();
// use an array instead
forkJoin([of(1), of(2)]).subscribe();
复制代码
在线例子:stackblitz.com/edit/forkjo…promise
Partition 可以将 source observable 分红两个 observables, 一个利用放知足时的预测值,一个是不知足时候的值。bash
好比页面中,当鼠标点击 h1 标题区域才是咱们想要的值,点击其余区域咱们依然作处理。函数
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')
}
});
复制代码
在线例子:stackblitz.com/edit/partit…fetch
combineLatest 目前只会保留 combineLatest([a, b, c])
这一种使用方法,缘由能够看 这里.
添加 scheduled 函数来建立 a scheduled observable of values。from、range等其余方法被废弃
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)
复制代码
输出结果是 1 3 2 在线例子:stackblitz.com/edit/schedu…
关于 Schedulers 的使用我会在后续文章中介绍