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

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 运算符:

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

您可以使用 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(...)

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

10-13 04:08