henorek
henorek

Reputation: 502

How to get some data from list and create another list with that data in RxJava

I have I case where I got one Object from API. This Object containts ArrayList. This ArrayList containts objects with data I need as another list.

I have this code and it works just fine

Observable<SomePresentationModel> observable = apiService.getData()
    .map(data -> {
      List<Foo> foo = new ArrayList<>();
      for (Bar bar : data.getBars()) {
        foo.addAll(bar.getSomething());
      }
      return asPresentationModel(foo);
    });

But it looks terrible and I'm sure there is some way to do it better but I don't know how, any ideas?

Upvotes: 0

Views: 55

Answers (1)

dwursteisen
dwursteisen

Reputation: 11515

You can use flatMapIterable / toList to emits item from your list, and rebuild a list after (see bellow). Please note that toList will work only if apiServiceService.getData() return an Observable that complete. Otherwise, it won't emit the list.

Observable<SomePresentationModel> observable = apiService.getData()
              .flatMapIterable(data -> data.getBars())
              .map(elt -> elt.getSomething())
              .toList()
              .map(foo -> asPresentationModel(foo)); 

Upvotes: 3

Related Questions