java - RxJava - 获取列表中的每一项

标签 java monads reactive-programming rx-java

我有一个返回 Observable<ArrayList<Long>> 的方法,这是一些项目的ID。我想浏览这个列表并使用另一种返回 Observable<Item> 的方法下载每个项目.

我将如何使用 RxJava 运算符来做到这一点?

最佳答案

这是一个独立的小例子

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。

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

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>

关于java - RxJava - 获取列表中的每一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035090/

相关文章:

java - Selenium 驱动程序选择错误

java - 如何将经纬度从 Leaflet CRS.Simple 转换为 EPSG :4326

scala - 使用任何 Monoid 通过键对值进行分组

java - Micronaut 中用于 RESTful API 的响应式(Reactive)方法/类型

java - 获取NoSuchBeanDefinitionException : No qualifying bean of type ServerRequest in Spring WebFlux

java - 如何在输出中随机生成字母?

java - 错误 "actual and format arguments lists differ in length"

haskell - 使用 Foldl 和 Reader monad 递归地遍历 AST,无需样板

haskell - 自定义数据类型(带有状态的+)的Monadic Haskell运算符

c# - 测试 ReactiveCommand 和 ReactiveObject ViewModel