2016-02-19 75 views
3

我使用Rx.Observable.create()創建了一個異步觀察數組,並希望在完成時使用.toArray()來獲取所有值。RxJS - 如何使用toArray()和異步observables數組?

console.log('running'); 
let valsArray = ['a','b','c'].map((val,i)=>{ 
    return Rx.Observable.create((obs)=>{ 
    let tid = setTimeout(()=>{ 
     console.log(val + ' timing out'); 
     obs.onNext(val); 
    },i*500); 
    return()=>{ 
     clearTimeout(tid); 
    }; 
    }).publish().refCount(); 
}); 

Rx.Observable.from(valsArray) 
.flatMap((v)=>v) 
.toArray() 
.subscribe((arr)=>{ 
    console.log("arr should be ['a','b','c']",arr); 
}); 

上面的例子在http://jsbin.com/wegoha/10/edit?js,console

使用setTimeout作爲其他異步操作的替身,以保持示例簡單。

+1

除非它支持您的問題中已有的信息,否則您不應鏈接到外部網站。 – Enigmativity

回答

5

該代碼是正確的,除非您沒有完成源observables。

toArray()運算符只有在observable完成時才能工作,並且由於您沒有完成Rx.Observable.create,因此您的查詢永遠不會結束。

試試這個:

console.log('running'); 
let valsArray = ['a','b','c'].map((val,i)=>{ 
    return Rx.Observable.create((obs)=>{ 
    let tid = setTimeout(()=>{ 
     console.log(val + ' timing out'); 
     obs.onNext(val); 
     obs.onCompleted(); 
    },i*500); 
    return()=>{ 
     clearTimeout(tid); 
    }; 
    }).publish().refCount(); 
}); 

Rx.Observable.from(valsArray) 
.flatMap((v)=>v) 
.toArray() 
.subscribe((arr)=>{ 
    console.log("arr should be ['a','b','c']",arr); 
}); 

而且,正如一個側面說明,.publish().refCount()似乎錯在這裏。在這段代碼中,不需要使源觀測數據變得很熱。

+0

謝謝。像魅力一樣工作,現在我更瞭解onCompleted方法。由於我沒有完全理解它們,所以再次檢查了熱和冷的可觀察文檔。神奇的描述在http://stackoverflow.com/questions/32190445/hot-and-cold-observables-are-there-hot-and-cold-operators – Adam

相關問題