How To Do Recursive Observable Call in RxJava?

后端 未结 1 1972
独厮守ぢ
独厮守ぢ 2021-01-02 07:15

I am quite new to RxJava (and Reactive paradigm in general), so please bear with me.

Suppose I have this News and this nested Comment data

相关标签:
1条回答
  • 2021-01-02 08:18

    This does practically the same thing described in the article:

    Observable<Comment> getInnerComments(Comment comment) {
        if (comment.childIds.length > 0)
            return Observable.merge(
                    Observable.just(comment),
                    Observable.from(comment.childIds)
                            .flatMap(id -> getComments(id))
                            .flatMap(this::getInnerComments));
        return Observable.just(comment);
    }
    
    public static void main(String[] args) {
        getComments(1)
              .flatMap(this::getInnerComments)
              .subscribe(c -> System.out.println(comment.toString()));
    }
    

    I start with the comment with id = 1, then I pass it to getInnerComments(). The getInnerComments() checks if the comment has children. If it does, it iterates over every child id (Observable#from) and loads every child with your getComments(int) API. Then every child is passed to the getInnerComments() to do the same procedure. If a comment doesn't have children, it is immediately returned using Observable#just.

    This is pseudo-code and it wasn't tested, but you should get the idea.


    Below is an example of how to get all comments and then aggregate them to one List<Comment>.

    getNews(99)
            .flatMap(news -> Observable.from(news.commentIds))
            .flatMap(commentId -> getComments(commentId))
            .flatMap(comment -> getInnerComments(comment))
            .toList()
            .subscribe(commentList -> { });
    
    0 讨论(0)
提交回复
热议问题