How to convert from Observable<List<X>> to Observable<List<Y>>, using a function that takes X as parameter & returns Observable<Y>

此生再无相见时 提交于 2020-01-25 07:23:23

问题


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

Observable<List<String>> getFriendUserIds()

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

Observable<Account> getAccount(String userId)

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

Example:

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

===>

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

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.


回答1:


Try this:

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

or this:

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


来源:https://stackoverflow.com/questions/48959354/how-to-convert-from-observablelistx-to-observablelisty-using-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!