使用RxJava获取对象,转换包含列表,并使用该列表。

9

我试图解决的高级问题是,使用RxJava将从FooContainer(Observable)获取的包含Foo对象的列表转换为FooBar对象的列表。

我的(困惑的)尝试:

fooContainerObservable
  .map(container -> container.getFooList())
  .flatMap(foo -> transformFooToFooBar(foo))
  .collect( /* What do I do here? Is collect the correct thing? Should I be using lift? */)
  .subscribe(fooBarList -> /* Display the list */);

我困惑的地方(至少之一)是将压平的列表转换回列表的步骤。

注意:我正在尝试在Android应用程序中完成此操作。


你能解释一下为什么你计划使用collect吗?如果你想要将所有的项收集到一个List中,只需调用toList即可。 - zsxwing
@zsxwing 因为我觉得从事件流中“收集”多个项目是有意义的 :). 我不知道 toList 的存在。如果你回答并建议使用它,我会将其标记为解决方案! - loeschg
1个回答

17

toList 可以将 Observable 中的所有项目收集到一个 List 中并发出它。虽然可以使用 collect 实现 toList,但它比 collect 要简单得多。对于您的示例,它将是:

fooContainerObservable
  .map(container -> container.getFooList())
  .flatMap(foo -> transformFooToFooBar(foo))
  .toList()
  .subscribe(fooBarList -> /* Display the list */);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接