【发布时间】:2018-11-21 10:07:48
【问题描述】:
我有一个带有好友连接的数据库表:
下一个示例只是一个Imagined 示例,所以请不要建议我以其他方式实现它。
朋友连接:
- 身份证
- humanId
我有一个包含这些 id 的列表。
val friendConnections = arrayListOf(
FriendConnection(id=10, humanId=141),
FriendConnection(id=13, humanId=142)
)
我想用 RxJava 制作这个结果列表。
val friendList = arrayListOf(
Friend(friendConnectionId = 10, humanId = 141, humanInstance = (...)),
Friend(friendConnectionId = 13, humanId = 142, humanInstance = (...))
)
我怎样才能得到一个人?
fun getHumanById(id: Long) : Single<Human>
所以我需要迭代friendConnections 并为每个人类进行一次调用。比我需要将带有新 Human 实例的 FriendConnection 映射到 Friend 实例。
我试过了,还是不行:
Observable.fromIterable(arrayListOf(
FriendConnection(id=10, humanId=141),
FriendConnection(id=13, humanId=142)
))
.flatMapSingle { friendConnection ->
repository.getHumanById(friendConnection.humanId)
?.map {human ->
Friend(friendConnection.id,friendConnection.humanId,human)
}
}
.toList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ it ->
Timber.i("friendList is here: $it")
}, {
throw it
})
有人知道出了什么问题吗? (我想用 Rx 实现它,而不是用 Room)
【问题讨论】:
-
你有什么结果?如果您有
fun getHumanById(id: Long) : Single<Human>签名,为什么在repository.getHumanById(friendConnection.humanId)?.map中使用安全调用? -
为什么你想用 Rx 做这个?您可以使用 kotlin 运算符本身来实现这一点。你的
repository.getHumanById是在调用 API 吗? -
不,这只是一个本地数据库调用。
-
你确定
fun getHumanById(id: Long)返回Single<Human>而不是Single<Human>?(可空类型)? -
因为在表达式中
repository.getHumanById(friendConnection.humanId)?.map {...}问号表示可以为空的类型。