Reputation: 1005
I have two method. Let it see the first one's model.
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
}
}
In this model. I have ownerid. I need to start a new call to get the owner's UserModel.
So:
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()
}
)
How can I use RXJava in chain? There is any good practice to do it? Thank you for any suggestions
Upvotes: 1
Views: 866
Reputation: 7649
You need the flatMap
operator:
commentRepository.getPostCommentsById(postId)
.flatMap { commentModel ->
userRepository.getUserDetailsByUid(commentModel.ownerid!!)
.map { userModel -> CommentWithOwnerModel(commentModel,usermodel) }
}
.subscribeOn(...)
.observeOn(...)
.subscribe(
{ view.loadComment(it) },
{ view.errorOnCommentsLoading() }
)
You can do it a bit more verbose (and easier to understand) with the 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(...)
Upvotes: 5