Skip to content

Instantly share code, notes, and snippets.

@bowmanb
Last active February 22, 2020 14:07
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bowmanb/a93185389210e3bd2eb8 to your computer and use it in GitHub Desktop.
Save bowmanb/a93185389210e3bd2eb8 to your computer and use it in GitHub Desktop.
RxJava collect() example. Converting a list of phrases into a list of their IDs only.
@Override
public void onNext(ArrayList<Phrase> phrases) {
ArrayList<Integer> phraseIDs = new ArrayList<>();
Observable
.from(phrases)
.collect(phraseIDs, new Action2<ArrayList<Integer>, Phrase>() {
@Override
public void call(ArrayList<Integer> integers, Phrase phrase) {
integers.add(phrase.getId());
}
})
.subscribe();
}
@ubaierbhat
Copy link

Can you show an example of how to do the same in RxJava2?

@pepela
Copy link

pepela commented Mar 22, 2018

        List<Integer> phraseIDs = new ArrayList<>();
        Observable.fromArray(phrases)
                .flatMapIterable(x -> x)
                .collect(() -> phraseIDs, (l, p) -> l.add(p.getId()))
                .subscribe();

@Ankhee
Copy link

Ankhee commented Oct 25, 2018

Thanks, this was helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment