我们提供两种版本进行对比
JS
// JS Array
const src = [1, 2, 3, 4, 5];
// map
const upper = src.map(n => n * 2);
upper.forEach(val => console.log('js-array', val));
const isEven = val => val % 2 === 0;
// filter
const even = src.filter(isEven);
even.forEach(val => console.log('js-array-even', val));
// reduce
const sum = src.reduce((a, b) => a + b);
console.log('sum', sum);
Observables
import { Observable } from 'rxjs';
import 'rxjs/add/observable/range';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/reduce';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/take';
// Observable
const src$ = Observable.range(1, 5);
// map
const upper$ = src$.map(n => n * 2);
const isEven = val => val % 2 === 0;
upper$.subscribe(val => console.log('observable', val));
// filter
const even$ = src$.filter(isEven);
even$.subscribe(val => console.log('observable-even', val));
// reduce
const sum$ = src$.reduce((acc, x) => acc + x);
sum$.subscribe(val => console.log('sum$', val));
⚠️ Observable 只有在至少有一个订阅的时候才会执行
执行结果
小小的进阶一下
// JS Array
const src = [1, 2, 3, 4, 5];
src.map(n => n * 2).filter(x => x % 2 === 0).forEach((val, idx) => {
if (idx <= 2 - 1) {
console.log('js', val);
}
});
// Observable
const src$ = Observable.range(1, 5);
src$.map(n => n * 2).filter(x => x % 2 === 0).
take(2).subscribe(val => console.log('observable', val));
const average$ = Observable
.range(0, 5)
.reduce((previous, current) => {
return {
sum: previous.sum + current,
count: previous.count + 1
};
}, { sum: 0, count: 0 })
.map(result => {
console.log('result', result);
return result.sum / result.count;
});
average$.subscribe(val => console.log('Average is ', val));
考虑一下如果有个sequence是无穷无尽的我们reduce永远在执行,我们如何获取某个点的计算结果呢?所幸的是我们可以使用scan来操作,下面我们来模拟一个无穷尽的sequence。
const averageScan$ = Observable.interval(1000)
.scan(
(previous, current) => {
return {
sum: previous.sum + current,
count: previous.count + 1
};
}, { sum: 0, count: 0 }
).map(result => result.sum / result.count);
averageScan$.subscribe(val => console.log('Average', val));
它会永远计算下去,我们每隔一秒获取一次结果。