【问题标题】:How to chain API requests using Kotlin Flow如何使用 Kotlin Flow 链接 API 请求
【发布时间】:2021-12-18 05:00:50
【问题描述】:

基于 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 并返回 Users 的列表?

【问题讨论】:

    标签: android kotlin reactive-programming kotlin-coroutines flow


    【解决方案1】:
    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)
        }
    }
    

    【讨论】:

    • 欢迎来到 Stack Overflow,感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地了解正在发生的事情,尤其是那些刚接触该语言并难以理解概念的社区成员。
    • 代码不言自明:)
    猜你喜欢
    • 2021-11-07
    • 2021-03-16
    • 2019-10-30
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多