如何从 Observable> 转换到 Observable<List<Y>,使用将 X 作为参数的函数 &返回 Observable
我有一个方法可以无限期地(非有限地)发出用户 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 Account
s 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()
);