RxAndroid response of one call to make another request

拟墨画扇 提交于 2020-01-06 08:21:12

问题


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);

 }


来源:https://stackoverflow.com/questions/36713433/rxandroid-response-of-one-call-to-make-another-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!