在 RxJava 中将 Observable 转换为集合

Héc*_*tor 2 rx-java

我想收集集合中发出的每个项目。我是这样做的:

List found = new ArrayList();
controller.search(query)
          .doOnCompleted(new Action0() {
            @Override
            public void call() {
                //Do something with "found" list
            }
        }).subscribe(new Action1<String>() {
            @Override
            public void call(String item) {
                found.add(item);
            }
        });
Run Code Online (Sandbox Code Playgroud)

是否有 RxJava 内置方法来执行此操作?

Joh*_*wUs 5

使用toList收集发射的字符串和EMIT它们作为一个单独的列表,一旦观察到完成如

controller.search(query)
          .toList()
          .subscribe(new Action1<List<String>>() {
            @Override
            public void call(List<String> found) {
                // Do something with the list
            }
        });
Run Code Online (Sandbox Code Playgroud)