如何使用 Kotlin Flow 链接 API 请求

How to chain API requests using Kotlin Flow

基于 ID 列表,我需要检索包含每个用户详细信息的用户列表。下面是我的模型的简化和 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()
}

在 RxJava 中我会做这样的事情:

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()

如何使用 Kotlin Flow 实现 UsersRepository 和 return User 的列表?

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)
    }
}