前端RxJs響應式程式設計之運算子實踐

welchang發表於2021-09-09

常用運算子

本地使用環境為rollup+rxjs,具體的rollup配置,請參考另一篇文章,這裡不再贅述。

import { of,Observable, interval,Subject ,from,bindCallback} from 'rxjs';
import { version } from './package.json';
import { ajax } from 'rxjs/ajax';
import { map, catchError } from 'rxjs/operators';

const someFunction = (a, b, c) => {
   console.log("a"); // 5
   console.log("b"); // 'some string'
   console.log("c"); // {someProperty: 'someValue'}
 };
  
 const boundSomeFunction = bindCallback(someFunction);
 boundSomeFunction().subscribe(values => {
   console.log(values) // [5, 'some string', {someProperty: 'someValue'}]
 });

from

//逐行輸出 1,2,3
import { from} from 'rxjs';
const arr = [1,2,3];
const result$ = from(arr);
result$.subscribe(res => console.log(res));

range

//逐行輸出 1-10
import { range } from 'rxjs';

const numbers = range(1, 10);
numbers.subscribe(x => console.log(x));

timer

//1 ....
import { timer } from 'rxjs';

const numbers = timer(3000,1000); //延遲3s,定時1s
numbers.subscribe(x => console.log(x+1));

interval

// 1....
import { interval } from 'rxjs';

const numbers = interval(1000);
numbers.subscribe(x => console.log(x+1));

of

// 輸出陣列  [1,2,3]
import { of } from "rxjs";

const arr = [1,2,3]
const result$ = of(arr);
result$.subscribe(res => console.log(res));

// 逐行1,2,3
const result$ = of(1,2,3);
result$.subscribe(res => console.log(res));

條件判斷

import { defer, fromEvent, interval,of } from 'rxjs';

const clicksOrInterval = defer(() => { //es6 支援
   return Math.random() > 0
   ? of('click')
   : interval(1000);
});
clicksOrInterval.subscribe(x => console.log(x));
import { defer, fromEvent, interval,of, iif } from 'rxjs';
let isFisrt;
const clicksOrInterval = iif(
   () => isFisrt,
   of('first'),
   of('second')
);
isFisrt = true;
clicksOrInterval.subscribe(x => console.log(x));

isFisrt = false;
clicksOrInterval.subscribe(x => console.log(x));

延遲

import { fromEvent ,of} from 'rxjs';
import { delay } from 'rxjs/operators';

const res = of(1,2,3);
const delayedClicks = res.pipe(delay(1000)); // each click emitted after 1 second
delayedClicks.subscribe(x => console.log(x));

防抖

import { fromEvent } from 'rxjs';
import { throttle } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const result = clicks.pipe(throttle(ev => interval(1000)));
result.subscribe(x => console.log(x));

map

import { of} from 'rxjs';
import { delay,map} from 'rxjs/operators'; //注意map引入

const res = of(1,2,3);
const delayedClicks = res.pipe(map(item => item * 2)); // each click emitted after 1 second
delayedClicks.subscribe(x => console.log(x));

filter

import { of} from 'rxjs';
import { delay,filter} from 'rxjs/operators';

const res = of(1,2,3);
const delayedClicks = res.pipe(filter(item => item % 2 === 0)); // each click emitted after 1 second
delayedClicks.subscribe(x => console.log(x));

本文作者:前端首席體驗師(CheongHu)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4830/viewspace-2824222/,如需轉載,請註明出處,否則將追究法律責任。

相關文章