【问题标题】:combine two lists and map to new class object with rxjava结合两个列表并使用 rxjava 映射到新的类对象
【发布时间】:2018-11-09 18:56:09
【问题描述】:

考虑以下输入:调用网络调用将检索客户端对象

data class Client(
val name: String,
val phoneNumber: String,
val frequentContacts: List<String>,
val allContacts: List<String>
)

我需要做的是在新对象中映射频繁联系人和 allContacts 列表中的相似名称并订阅输出。

假设来自网络调用的响应将返回此客户端对象

{
"name": "Jack",
"phoneNumber": "90284302424",
"frequentContacts": [
    "John",
    "Sam"
    ],
"allContacts": [
    "John",
    "Adam",
    "Peter",
    "Kim",
    "Sam"
    ]
}

我需要在订阅新创建对象时收到什么。

data class clientViewModel(val name: String,val isFrequent: Boolean)

所以在 onSuccess 中我应该有来自 clientViewModel 的实例

预期输出:

(“约翰”,真“)

("亚当", 假")

("彼得", 假")

("金", 假")

(“山姆”,真“)

我在做什么

clientRepository.getClientById(clientId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate { view.hideProgress() }
.flatMap{it.frequentContacts}
.subscribe{
onSuccess(item: ClientViewModel){}
onError(){}
onFinish(){}
}

但这不起作用,因为一旦我使用平面地图,我就会丢失 allContacts 列表 有什么帮助吗?

我了解了 GroupBy 运算符,但我使用的是 Single...

【问题讨论】:

  • 你怎么看:.flatMap{it.allContacts.map{c-&gt;Pair(c,it.frequentContacts.contains(c))} }
  • @Raphael 我试过它显示我键入未匹配错误必需:SingleSource 找到:List

标签: kotlin rx-java2


【解决方案1】:

老实说,我会这样做:

clientRepository.getClientById(clientId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doFinally { view.hideProgress() }
.map { client ->
    client.allContacts.map { contact ->
        clientViewModel(name = contact, isFrequent = client.frequentContacts.contains(contact))
    }
}
.subscribeBy(onSuccess = { list: List<clientViewModel> -> 
    ...
}, onError = { err -> ... })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多