0

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.

Ehtesham Hasan
  • 4,133
  • 2
  • 23
  • 31
  • Simply apply `toList` to the flow you discovered in that question's answer. – akarnokd Feb 24 '18 at 10:44
  • @akarnokd But `toList` will convert it to `Single`, and has additional requirements for the source `Observable` to be finite. `getFriendUserIds()` is an infinite source. – Ehtesham Hasan Feb 24 '18 at 11:18
  • 1
    Please familiarize yourself with the available operators of RxJava - it will save you a lot of time. In this case, you'd need `take(1)` to limit the source and `toObservable()` to convert back to `Observable`. – akarnokd Feb 24 '18 at 11:25
  • @akarnokd I edited the question, please take another look. – Ehtesham Hasan Feb 24 '18 at 12:39

1 Answers1

3

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()
);
akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • Thanks for the suggestions, but the 1st solution will take only the 1st element (["JohnId", "LisaId"] in the example), return the Accounts in a list ([, ]) and **complete**. I am looking for an output stream that **never completes**. – Ehtesham Hasan Feb 25 '18 at 05:40
  • Second solution is the one I was looking for! Thanks for the help and respect for your work with RxJava! – Ehtesham Hasan Feb 25 '18 at 13:22