2017-09-06 44 views
3

有潛在異步觀察到,即是這樣的:讓潛在異步RxJS觀察到的肯定異步

const potentiallyButNotNecessarilyAsyncObservable = [ 
    Observable.of('sync'), 
    Observable.of('async').delay(100) 
][Math.round(Math.random())]; 

potentiallyButNotNecessarilyAsyncObservable.subscribe(console.log); 

應該做異步觀察到。如果它已經是異步的,不要再拖延它,所以我不能做potentiallyButNotNecessarilyAsyncObservable.delay(0)

這怎麼辦?

+0

你能更好地解釋你在「同步」和「異步」觀察結果中看到的差異嗎? –

+0

據我所知,沒有「同步」可觀察對象,因爲如果不訂閱和傳遞將異步執行的回調(取決於您的調度程序),您將無法檢索它的值 –

+0

@OlesSavluk上面的示例中顯示了'sync'可觀察對象。 'Observable.of('sync')。subscribe(...)'會在同一個tick上立即發出一個值。 – estus

回答

2

您可以通過使用調度程序來控制如何安排和執行工作。例如,您可以編寫.observeOn(Rx.Scheduler.async),並且將使用setTimeoutsetInterval而不是同步遞歸調用來安排工作。這是高級主題,如果你想更好地瞭解它我建議你讀this great documentation on Schedulers

這裏有兩個例子,第一個是在一個蜱執行,第二次在幾個:

const sync$ = Rx.Observable.of('sync'); 
 

 
// by default RxJS will pick a default scheduler by using the principle of least concurrency 
 
// in this case it is a null or undefined Schedulr which means notifications are delivered synchronously and recursively 
 
console.log('--------- default(null) Scheduler ---------------'); 
 
console.log('just before subscribe'); 
 
sync$.subscribe({ 
 
    next: x => console.log('got value ' + x), 
 
    error: err => console.error('something wrong occurred: ' + err), 
 
    complete:() => console.log('done'), 
 
}); 
 
console.log('just after subscribe'); 
 

 

 
const async$ = sync$.observeOn(Rx.Scheduler.async); 
 

 
// "got value sync" is printed after "just after subscribe" 
 
console.log('--------- Rx.Scheduler.async Scheduler ----------'); 
 
console.log('just before subscribe'); 
 
async$.subscribe({ 
 
    next: x => console.log('got value ' + x), 
 
    error: err => console.error('something wrong occurred: ' + err), 
 
    complete:() => console.log('done'), 
 
}); 
 
console.log('just after subscribe');
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

+0

是的,這個問題涉及默認調度程序提供的行爲。事實上,'Scheduler.async'是解決方案。謝謝。 – estus