-->

RxAndroid response of one call to make another req

2019-09-07 09:31发布

问题:

I'm new to RxAndroid and trying to chain responses.

I'm using this github API to retrieve data. Along with each issue there are comments link and events link associated with it which I want to fetch and update existing object with list of comments and events to form something like this.

[

issue: {

 comments: [

    {
     .
     .
    },
    {
     .
     .
    }
 ]

events : [

    {
     .
     .
    },
    {
     .
     .
    }
 ]

]

]

I could retrieve initial response with following code

GitHubService gitHubService = ServiceFactory.createServiceFrom(GitHubService.class, GitHubService.ENDPOINT);

    gitHubService.getIssuesList()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .map(issues -> Arrays.asList(issues))
            .subscribe(adapter::add);

Now How do I retrieve comments and events before updating adapter ? I want to show 3 comments and 3 events as well.

回答1:

Thanks to @Riccardo Ciovati for your example !

Here is my solution. and it works perfectly !

public static void getIssuesForRepo(final IssuesListAdapter adapter) {

    GitHubService gitHubService = ServiceFactory.createServiceFrom(GitHubService.class, GitHubService.ENDPOINT);

    gitHubService.getIssuesList()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .map(issues -> Arrays.asList(issues))
            .flatMap(issues -> Observable.from(issues))
            .filter(issue -> issue.getCommentsUrl() != null)
            .flatMap(new Func1<Issue, Observable<Issue>>() {
                @Override
                public Observable<Issue> call(Issue issue) {


                    return gitHubService.getComments(issue.getNumber())
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .map(comments -> {

                                issue.setCommentList(Arrays.asList(comments));

                                return issue;
                            });
                }


            })
            .toList()
            .subscribe(adapter::add);

}

where

public interface GitHubService {

  String ENDPOINT = "https://api.github.com/";

  @GET("repos/crashlytics/secureudid/issues")
  Observable<Issue[]> getIssuesList();

  @GET("repos/crashlytics/secureudid/issues/{number}/comments")
  Observable<Comment[]> getComments(@Path("number") long number);

 }