What’s New in RxJS v6 5

翻譯自原文:netbasal.com/whats-new-i…react

RxJS 已於上月2019.4.23發佈。 來看下帶來了哪些新功能git

New Fetch Observable

基於原生的 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 加強

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 Observable

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 目前只會保留 combineLatest([a, b, c]) 這一種使用方法,緣由能夠看 這裏.

Schedulers

添加 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 的使用我會在後續文章中介紹

相關文章
相關標籤/搜索