Héctor Valls
Héctor Valls

Reputation: 26084

Convert Observable to Collection in RxJava

I want to collect every item emitted in a Collection. I'm doing it this way:

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);
            }
        });

Is there a RxJava built-in way to carry this out?

Upvotes: 2

Views: 5006

Answers (2)

paul
paul

Reputation: 13481

If your search Query return a collection you can use scan operator to merge list for every item emitted.

@Test
public void collectCollections() {
    Observable.from(Arrays.asList(1, 2, 3))
              .map(Arrays::asList)
              .scan(new ArrayList<Integer>(), (l1, l2) -> {
                  l1.addAll(l2);
                  return l1;
              }).subscribe(System.out::println);
}

You can see more examples here https://github.com/politrons/reactive

Upvotes: 3

JohnWowUs
JohnWowUs

Reputation: 3083

Use toList to collect the emitted strings and an emit them as a single list once the observable completes e.g.

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

Upvotes: 5

Related Questions