问题
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 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.
回答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