gpt4 book ai didi

android - RxJava - 链式调用

转载 作者:行者123 更新时间:2023-11-29 14:59:51 31 4
gpt4 key购买 nike

我有两种方法。让它看到第一个的模型。

open class CommentModel {
var postid: String? = null
var ownerid: String? = null
var created: Date? = null
var message: String? = null

constructor() {
}

constructor(postid: String?, ownerid: String?, message: String?, created: Date?) {
this.ownerid = ownerid
this.created = created
this.postid = postid
this.message = message
}
}

在这个模型中。我有 ownerid。我需要开始新的通话以获取所有者的 UserModel。

所以:

   commentRepository.getPostCommentsById(postId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ commentModel ->
// it = the owner of comment.
userRepository.getUserDetailsByUid(commentModel.ownerid!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ userModel ->
val comment = CommentWithOwnerModel(commentModel,usermodel)
view.loadComment(comment)
},
{
}
)
},
{
view.errorOnCommentsLoading()
}
)

如何在链中使用 RXJava?有什么好的做法吗?感谢您的任何建议

最佳答案

您需要 flatMap运算符(operator):

 commentRepository.getPostCommentsById(postId)
.flatMap { commentModel ->
userRepository.getUserDetailsByUid(commentModel.ownerid!!)
.map { userModel -> CommentWithOwnerModel(commentModel,usermodel) }
}
.subscribeOn(...)
.observeOn(...)
.subscribe(
{ view.loadComment(it) },
{ view.errorOnCommentsLoading() }
)

你可以用 share 做的更详细一点(也更容易理解)运算符(operator):

val commentObs = commentRepository.getPostCommentsById(postId).share()
val userObs = commentObs.flatMap { userRepository.getUserDetailsByUid(it.ownerid!!) }
val commentWithOwnerObs = Single.zip(commentObs, userObs,
// Not using any IDE so this line may not compile as is :S
{ comment, user -> CommentWithOwnerModel(comment, user) } )
commentWithOwnerObs
.subscribeOn(...)
.observeOn(...)
.subscribe(...)

关于android - RxJava - 链式调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49349629/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com