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

2022-09-01 00:02:36

我有一个返回的方法,它是某些项目的ID。我想浏览此列表并使用返回.Observable<ArrayList<Long>>Observable<Item>

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


答案 1

下面是一个独立的小示例

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);
    }
}

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

这应该给你你需要的基础。

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>

答案 2

作为替代方案,您可以使用flatMap执行此操作:flatMapIterable

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
}

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

区别似乎是顺序(RxJava2):

  • Observable.fromIterable:将可迭代序列转换为发出序列中项的 ObservableSource。
  • Observable.flatMapIterable:返回一个 Observable,该可观察对象将源 ObservableSource 发出的每个项与选择器生成的该项对应的 Iterable 中的值合并。

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

Observable.just(Arrays.asList(1, 2, 3))
            .flatMap(Observable::fromIterable)
            .flatMap(this::downloadFoo)

推荐