Ishita Garg
Ishita Garg

Reputation: 95

RxAndroid: Fetch data from multiple apis

I have a usecase where I get list of userids from 1 Api as a Single<List> and I need to fetch all the users from a different Api which returns Single.

fun fetchUserIds(): Single<List<String>>

fun fetchUser(id: String): Single<User>

I need to return a List eventually. What is the ideal way to do this using RxJava?

Upvotes: 1

Views: 55

Answers (1)

taygetos
taygetos

Reputation: 3040

You can use Flowable to iterate over the userIds and call the fetchUser on each element. Then you can combine the result (e.g toList or collect):

fetchUserIds()
  .flatMap(ids -> Flowable.fromIterable(ids).flatMapSingle(this::fetchUser).toList())
  .subscribe(users -> {
      //list of users
   });

Upvotes: 1

Related Questions