k_wisniewski k_wisniewski - 1 year ago 54
Java Question

RxJava - fetch every item on the list

I have a method that returns an

, which are ids of some Items. I'd like to go through this list and download every Item using another method that returns

How would I do this using RxJava operators?

Answer Source

Here's a small self contained example

public class Example {

    public static class Item {
        int id;

    public static void main(String[] args) {
                .flatMapIterable(ids -> ids) // Converts your list of ids into an Observable which emits every item in the list
                .flatMap(Example::getItemObservable) // Calls the method which returns a new Observable<Item>
                .subscribe(item -> System.out.println("item: " + item.id));

    // Simple representation of getting your ids.
    // Replace the content of this method with yours
    private static Observable<List<Integer>> getIds() {
        return Observable.just(Arrays.<Integer>asList(1, 2, 3));

    // Replace the content of this method with yours
    private static Observable<Item> getItemObservable(Integer id) {
        Item item = new Item();
        item.id = id;
        return Observable.just(item);

Please note that Observable.just(Arrays.<Integer>asList(1, 2, 3)) is a simple representation of Observable<ArrayList<Long>> from your question. You can replace it with your own Observable in your code.

This should give you the basis of what you need.

p/s : Use flatMapIterable method for this case since it belongs to Iterable as below explaining:

 * Implementing this interface allows an object to be the target of
 * the "for-each loop" statement. See
 * <strong>
 * <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides /language/foreach.html">For-each Loop</a>
 * </strong>
 * @param <T> the type of elements returned by the iterator
 * @since 1.5
 * @jls 14.14.2 The enhanced for statement
 public interface Iterable<T>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download