我正在使用RxJAva的Retrofit作为获取Rss Feeds的应用程序,但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());
}
干净吗?有没有更好的办法 ?
答案 0 :(得分:1)
让我们看看......
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;以上将同时对网络进行所有呼叫。