Home > Software engineering >  RxAndroid: Fetch data from multiple apis
RxAndroid: Fetch data from multiple apis

Time:11-12

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?

CodePudding user response:

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
   });
  • Related