vih*_*kat 1 android kotlin rx-java2
我有两种方法。让它看到第一个的模型。
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
}
}
Run Code Online (Sandbox Code Playgroud)
在这个模型中。我有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()
}
)
Run Code Online (Sandbox Code Playgroud)
如何在链中使用 RXJava?有什么好的做法可以做到吗?谢谢你的任何建议
您需要flatMap操作员:
commentRepository.getPostCommentsById(postId)
.flatMap { commentModel ->
userRepository.getUserDetailsByUid(commentModel.ownerid!!)
.map { userModel -> CommentWithOwnerModel(commentModel,usermodel) }
}
.subscribeOn(...)
.observeOn(...)
.subscribe(
{ view.loadComment(it) },
{ view.errorOnCommentsLoading() }
)
Run Code Online (Sandbox Code Playgroud)
您可以使用share运算符将其做得更详细(并且更容易理解):
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(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
745 次 |
| 最近记录: |