Home > Back-end >  How to chain API requests using Kotlin Flow
How to chain API requests using Kotlin Flow

Time:11-04

Based on a list of ids I need to retrieve a list of users with detailed informaiton of each user. Below a simplification of my models and API;

data class UserDTO(val id: String)
data class PetDTO(val name: String)

interface Api {
  suspend fun users(): List<UserDTO>
  suspend fun pets(userId: String): List<PetDTO>
}

data class User(
  val id: String,
  val pets: List<Pet>
)

data class Pet(val name: String)

class UsersRepository(api: Api) {
  val users: Flow<List<User>> = TODO()
}

In RxJava I would do something like this:

val users: Observable<List<User>> = api.users()
  .flatMapIterable { it }
  .concatMap { userDto ->
    api.pets(userDto.id)
      .map { petsListDto ->
        User(userDto.id, petsListDto.map { Pet(it.name) })
      }
  }.toList()

How can I implement UsersRepository and return the list of Users using Kotlin Flow?

CodePudding user response:

class UsersRepository(api: Api) {
    val users: Flow<List<User>> = flow {
        val usersWithPets = api.users().map { userDto ->
            val pets = api.pets(userDto.id).map { petsListDto ->
                Pet(petsListDto.name)
            }
            User(userDto.id, pets)
        }
        emit(usersWithPets)
    }
}
  • Related