RxJava - 获取列表中的每个项目

k_w*_*ski 41 java monads reactive-programming rx-java

我有一个返回an的方法Observable<ArrayList<Long>>,它是一些Items的id.我想通过这个列表并使用另一个返回的方法下载每个Item Observable<Item>.

我如何使用RxJava运算符执行此操作?

Mig*_*gne 51

这是一个小小的自包含示例

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<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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这Observable.just(Arrays.<Integer>asList(1, 2, 3))Observable<ArrayList<Long>>您问题的简单表示.您可以在代码中使用自己的Observable替换它.

这应该为您提供所需的基础.

p/s:flatMapIterable本案例的使用方法,因为它属于Iterable如下解释:

/**
 * 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>
Run Code Online (Sandbox Code Playgroud)

  • 您也可以执行Observable.from(Arrays。&lt;Integer&gt; asList(...)),而不需要flatMapIterable (2认同)

pat*_*ckf 5

作为替代方案,flatMapIterable您可以使用以下方法flatMap:

Observable.just(Arrays.asList(1, 2, 3)) //we create an Observable that emits a single array
            .flatMap(numberList -> Observable.fromIterable(numberList)) //map the list to an Observable that emits every item as an observable
            .flatMap(number -> downloadFoo(number)) //download smth on every number in the array
            .subscribe(...);


private ObservableSource<? extends Integer> downloadFoo(Integer number) {
   //TODO
}
Run Code Online (Sandbox Code Playgroud)

我个人认为.flatMap(numberList -> Observable.fromIterable(numberList))比阅读和理解更容易.flatMapIterable(numberList -> numberList ).

差异似乎是订单(RxJava2):

  • Observable.fromIterable:将Iterable序列转换为发出序列中项目的ObservableSource.
  • Observable.flatMapIterable:返回一个Observable,它将源ObservableSource发出的每个项目与Iterable中与选择器生成的项目对应的值合并.

使用方法引用,如下所示:

Observable.just(Arrays.asList(1, 2, 3))
            .flatMap(Observable::fromIterable)
            .flatMap(this::downloadFoo)
Run Code Online (Sandbox Code Playgroud)