2016-02-19 127 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

相关问题