获取列表中的每个项目

获取列表中的每个项目

本文介绍了RxJava - 获取列表中的每个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 Observable< ArrayList< Long>> 的方法,它们是某些项目的ID。我想通过此列表并使用另一种方法下载每个项目,该方法返回 Observable< Item>

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

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

How would I do this using RxJava operators?

推荐答案

这是一个小的自包含示例

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<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。 just(Arrays。< Integer> asList(1,2,3)) Observable< ArrayList< Long>> 的简单表示从你的问题。您可以在代码中用自己的Observable替换它。

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:对于这种情况使用 flatMapIterable 方法,因为它属于 Iterable ,如下所示:

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>

这篇关于RxJava - 获取列表中的每个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 13:25