我有一个返回 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/