from RxJS Observables vs Promises
根據以上影片
本文稍做修改來介紹Reactive與Promise的差異
先看以下sample
console.clear();
var promise = new Promise((resolve) => {
setTimeout(() => {
resolve(42);
}, 500);
console.log('promise started');
});
promise.then(x => console.log(x));
var source = Rx.Observable.create((observer) => {
setTimeout(() => {
observer.onNext(43);
}, 400);
console.log('observable started');
});
source.forEach(x => console.log(x));
console
"promise started"
"observable started"
43
42
依序promise.then行為及訂閱或觀察Observable source.forEach
初始化分別印出promise started及observable started
然後再印出43之後才是42
因為source的timeout時間較promise的短
###Lazy
console.clear();
var promise = new Promise((resolve) => {
setTimeout(() => {
console.log('promise timeout hit');
resolve(42);
}, 500);
console.log('promise started');
});
// promise.then(x => console.log(x));
var source = Rx.Observable.create((observer) => {
setTimeout(() => {
observer.onNext(43);
}, 400);
console.log('observable started');
});
// source.forEach(x => console.log(x));
console
"promise started"
"promise timeout hit"
由此可以看到
當new Promise物件就會執行初始化印出promise started
並且在500毫秒時印出promise timeout hit
但因為註解promise.then行為所以不會取x值印出42
而另一方面註解訂閱或觀察Observable
則不會執行初始化當然也就不會印出observable started及43
###Disposable, Repeatable, Retry
console.clear();
var promise = new Promise((resolve) => {
setTimeout(() => {
console.log('promise timeout hit');
resolve(42);
}, 1000);
console.log('promise started');
});
promise.then(x => console.log(x));
promise.then(x => console.log(x));
var source = Rx.Observable.create((observer) => {
var id = setTimeout(() => {
console.log('observable timeout hit');
observer.onNext(43);
}, 800);
console.log('observable started');
return () => {
console.log('dispose called');
// clearTimeout(id);
};
});
var disposable = source.forEach(x => console.log(x));
setTimeout(() => {
disposable.dispose();
}, 500);
source.forEach(x => console.log(x));
console
"promise started"
"observable started"
"observable started"
"dispose called"
"observable timeout hit"
"observable timeout hit"
43
"promise timeout hit"
42
42
一開始訂閱或觀察Observable
所以會初始化印出observable started
disposable物件在500毫秒後會先呼叫dispose
然後印出dispose called
之後800毫秒時
因為Observable已經被dispose
所以只會印出observable timeout hit
而不會有onNext行為
但是為了驗證Observable可以repeatable及retry
最後一行再訂閱或觀察Observable source.forEach
則這次不但再次印出observable timeout hit
也會執行onNext行為印出43
至於promise初始化印出promise started後
1000毫秒時印出promise timeout hit
即使有2次promise.then行為仍只會得到2次x值42
並不會再次印出promise timeout hit
這是Promise與Observable差別所在
##Promise
- Scala: Future
- Java: CompletableFuture
- C#: Task
Promise相關的term在不同語言