可观察<Array<T>> 到可观察<T>

Observable<Array<T>> to Observable<T>

问题很简单:如何从 Observable<Array<T>> 转换为 Observable<T>

如果你能用 rxJS 或 RxJava 写答案,我将不胜感激,但任何其他语言都很好。

根据您想要的结果,有多种方法可以解决您的问题。这是一个 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]
});

对于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 -> {});