RxJava - 链式调用

时间:2018-03-18 15:26:01

标签: 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
    }
}

在这个模型中。我有主人。我需要开始一个新的调用来获取所有者的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? 这有什么好的做法吗?感谢您的任何建议

1 个答案:

答案 0 :(得分:4)

您需要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(...)