【问题标题】:Combine two variables in one request using Rx使用 Rx 在一个请求中合并两个变量
【发布时间】:2020-05-08 10:21:08
【问题描述】:

我想将 company 和 workFor 变量合并到一个流中,但我不知道如何。我尝试使用 switchMap、zip、merge 和 concatMapIterable,但没有任何效果。或者我做错了什么..

我的数据模型:

 data class UserCompany(
    @field:Json(name = "user") val user: User,
    @field:Json(name = "company") val company: Company,
    @field:Json(name = "workFor") val workFor: List<Company>
)

还有我当前的代码:

    authApi.getCompany(getJwt()) //here I get data that looks like the above model
           .subscribeOn(Schedulers.io())
           .flatMapIterable { 
                return@flatMapIterable it.data.workFor.toMutableList().add(it.data.company) //error Type mismatch
           },

//should returns stream of company and workFor

如何使用 Rx 组合来自一个请求的两个变量?

编辑,更好的例子。 假设我们有:

data class Pet(val name: String)

data class PetResult(
    val myPet: Pet, //dog
    val otherPet: List<Pet> //cat, bird, cow
)

我想得到这样的东西:

authApi.getPet() // response looks like PetResult (model above)
    .subscribeOn(Schedulers.io())
    .subscribe(
        { petList.setSuccess(it) }, // should returns dag, cat, bird, cow
        { petList.setError(it.message) }
    )

那么,如何将 myPet 与我从一个 API 请求中获得的 otherPet 合并?

【问题讨论】:

    标签: android rx-java rx-java2 rx-android


    【解决方案1】:

    你可以像下面这样实现上面的例子:

        apiClient.getPet.flatMap {
            var getListResponse=it;  
            //From getListResponse you will get Result obj which contain pet and other pet list
            var pet=it.getPet()
            var petList=it.getPetList()
            petList.add(pet)
            getListResponse.setPetList=petList
    
        }
    

    【讨论】:

    • 感谢您的回答,但我的意思是别的,我添加了一个更好的例子
    • 谢谢,我正在寻找复杂的解决方案,它是如此简单-.-
    猜你喜欢
    • 1970-01-01
    • 2012-07-30
    • 2019-05-11
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多