How to convert from Observable> to Observabl

2019-08-25 05:02发布

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条回答
趁早两清
2楼-- · 2019-08-25 05:50

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()
);
查看更多
登录 后发表回答