我使用Retrofit with RxJAva作为一个获取Rss提要的应用程序,但是Rss不包含所有信息,所以我使用jsoup来解析每个项目链接,以检索图像和文章的描述。现在我是这样使用的:
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());
}
检查的类来自rxJava-extras,但是您可以轻松地自己编写一个。是的,Java 8确实对Rx有帮助;