RxJava - fetch every item on the list

前端 未结 5 414
渐次进展
渐次进展 2020-12-13 08:43

I have a method that returns an Observable>, which are ids of some Items. I\'d like to go through this list and download every Item

5条回答
  •  天命终不由人
    2020-12-13 09:34

    Here's a small self contained example

    public class Example {
    
        public static class Item {
            int id;
        }
    
        public static void main(String[] args) {
            getIds()
                    .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
                    .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> getIds() {
            return Observable.just(Arrays.asList(1, 2, 3));
        }
    
        // Replace the content of this method with yours
        private static Observable getItemObservable(Integer id) {
            Item item = new Item();
            item.id = id;
            return Observable.just(item);
        }
    }
    

    Please note that Observable.just(Arrays.asList(1, 2, 3)) is a simple representation of Observable> 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
     * 
     * For-each Loop
     * 
     *
     * @param  the type of elements returned by the iterator
     *
     * @since 1.5
     * @jls 14.14.2 The enhanced for statement
      */
     public interface Iterable
    

提交回复
热议问题