如何从 Observable<List<X>> 转换到 Observable&lt;List&lt;Y&gt;,使用将 X 作为参数的函数 &amp;返回 Observable<Y> [英] How to convert from Observable&lt;List&lt;X&gt;&gt; to Observable&lt;List&lt;Y&gt;&gt;, using a function that takes X as parameter &amp; returns Observable&lt;Y&gt;

查看:45
本文介绍了如何从 Observable<List<X>> 转换到 Observable&lt;List&lt;Y&gt;,使用将 X 作为参数的函数 &amp;返回 Observable<Y>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以无限期地(非有限地)发出用户 ID 列表.

I have a method that emits a list of user ids, indefinitely (not finite).

Observable<List<String>> getFriendUserIds()

另一种返回特定用户 ID 的 Account 数据的方法.

And another method that returns Account data for a specific user id.

Observable<Account> getAccount(String userId)

我需要获取 getFriendUserIds() 方法返回的所有用户 ID 的 Account 数据,将它们分组在一个与用户 ID 列表相对应的列表中.

I need to get the Account data for all the user ids returned by the getFriendUserIds() method, grouped together in a list corresponding to the user id list.

基本上,我需要以下内容,最好以非阻塞方式.

Basically, I need the following, preferably in a non-blocking way.

Observable<List<String>> // infinite stream
===> *** MAGIC + getAccount(String userId) ***  
===> Observable<List<Account>> // infinite stream

示例:

["JohnId", "LisaId"]---["PaulId", "KimId", "JohnId"]------["KimId"]

===>

[<JohnAccount>, <LisaAccount>]---[<PaulAccount>, <KimAccount>, <JohnAccount>]------[<KimAccount>]

排序并不重要,但 List 必须包含与 List 中存在的每个用户 ID 相对应的 Account.

Ordering is not important but the List<Account> must contain Accounts corresponding to every user id present in List<String>.

**注意这个问题类似于这个问题,但需要额外要求将结果项重新分组到列表中.

**Note that this question is similar to this question, but with additional requirements to group the resulting items back in a list.

推荐答案

试试这个:

Observable<List<Account>> accountsList = getFriendUserIds()
.take(1)
.flatMapIterable(list -> list)
.flatMap(id -> getAccount(id))
.toList()
.toObservable();

或者这个:

Observable<List<Account>> accountsList = getFriendUserIds()
.flatMapSingle(list -> 
     Observable.fromIterable(list)
     .flatMap(id -> getAccount(id))
     .toList()
);

这篇关于如何从 Observable<List<X>> 转换到 Observable&lt;List&lt;Y&gt;,使用将 X 作为参数的函数 &amp;返回 Observable<Y>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆