RxJS
Observables
可以被取消
需要時才執行
code:javascript
let Observable = Rx.Observable;
let resultA, resultB, resultC;
function addAsync(num1, num2) {
const promise = fetch(http://example.com?num1=${num1}&num2=${num2}).then(
(x) => x.json()
);
return Observable.fromPromise(promise);
}
addAsync(1, 2)
.do((x) => (resultA = x))
.flatMap((x) => addAsync(x, 3))
.do((x) => (resultB = x))
.flatMap((x) => addAsync(x, 4))
.do((x) => (resultC = x))
.subscribe((x) => {
console.log("total", x);
console.log(resultA, resultB, resultC);
});
Observable.fromPromise
將Promise轉換成observable stream
.do和.flatMap是Observable的運算子