RxJava android 链接请求

RxJava android chaining requests

我将 Retrofit 与 RxJAva 一起用于获取 Rss 提要的应用程序,但 rss 不包含所有信息,因此我使用 jsoup 解析每个项目 link,以检索图像和文章的描述。现在我这样使用它:

    public Observable<Rss> getDumpData() {
    System.out.println("in the getDumpData");
    if (newsAppService == null) {
        System.out.println("newsAppServer is null");
    }
    return newsAppService.getDumpData()
            .flatMap(new Func1<Rss, Observable<Rss>>() {
                @Override
                public Observable<Rss> call(Rss rss) {
                    List<Item> items = new ArrayList<Item>();
                    for (int i = 0; i < rss.channel.items.size(); i++) {
                        Document document = null;
                        try {
                            document = Jsoup.connect(rss.channel.items.get(i).link).get();
                            Element element = document.select("div[itemprop=image] > img").first();
                            Element bodyElement = document.select("div[class=articlebody]").first();
                            System.out.println("got element " +bodyElement.toString());
                            rss.channel.items.get(i).image = element.attr("src");
                            items.add(rss.channel.items.get(i));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                    rss.channel.items = items;
                    rss.version = "Mams :D";
                    return Observable.just(rss);
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}

干净吗?有没有更好的办法 ?

让我们看看...

public Observable<Rss> getDumpData() {
  System.out.println("in the getDumpData");
  if (newsAppService == null) {
    System.out.println("newsAppServer is null");
  }
  return newsAppService.getDumpData()
     .flatMap(rss -> Observable
       .from(rss.channel.items)
       .observeOn(Schedulers.io())
       .flatMap(Checked.f1(item -> Observable
         .just(Jsoup.connect(item.link).get())
         .map(document -> document.select("div[itemprop=image] > img").first())
         .doOnNext(element -> item.image=element.attr("src"))
        ))
      )
      .ignoreElements()
      .defaultIfEmpty(rss)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread());
}

检查的 class 来自 rxJava-extras,但您可以轻松地自己编写一个。是的,Java 8 确实有助于 Rx;以上将同时对网络进行所有调用。