2017-08-04 96 views
0

問題很簡單:如何將Observable<Array<T>>轉換爲Observable<T>Observable <Array<T>> to Observable <T>

如果您可以用rxJS或RxJava編寫答案,但其他任何語言都不錯,我將不勝感激。

+1

什麼是你的目標是什麼?將數組中的每個元素作爲單獨的事件發出? –

+0

認爲flatmap是合適的 –

+0

應該有一個'flatMapIterable',它可以做你想做的。 –

回答

1

對於Java,Observable.from()是你想要什麼:

Observable<List<String>> listObservable = Observable.just(Arrays.asList("why", "hello", "there")); 

listObservable.flatMap(Observable::from) 
       .subscribe(str -> System.out.print(str + "-"), 
         throwable -> {}); 
2

根據您想要的結果,有很多方法可以解決您的問題。這裏是一個fiddle

console.clear(); 

var x = Rx.Observable.of([1, 2, 3], [4, 5, 6]); 

x.subscribe(item => { 
    console.log('Without flatMap: ' + JSON.stringify(item)); 
    //Without flatMap: [1, 2, 3] 
    //Without flatMap: [4, 5, 6] 
}); 

x.flatMap(item => { 
    return item; 
    } 
).subscribe(item => { 
    console.log('With flatMap: ' + item); 
    //With flatMap: 1 
    //With flatMap: 2 
    //With flatMap: 3 
    //With flatMap: 4 
    //With flatMap: 5 
    //With flatMap: 6 
}); 

x.reduce((a, b) => { 
    return a.concat(b); 
}).subscribe(item => { 
    console.log('With reduce: ' + JSON.stringify(item)); 
    //With reduce: [1, 2, 3, 4, 5, 6] 
}); 

x.scan((a, b) => { 
    return a.concat(b); 
}).subscribe(item => { 
    console.log('With scan: ' + JSON.stringify(item)); 
    //With scan: [1, 2, 3] 
    //With scan: [1, 2, 3, 4, 5, 6] 
}); 
相關問題