gpt4 book ai didi

java - RxAndroid,结合多个网络调用

转载 作者:行者123 更新时间:2023-11-30 11:05:39 24 4
gpt4 key购买 nike

public List<Office> getOffices(){

final List<Office> offices = new ArrayList<>();

Observable observable = Observable.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
for(String[] of : backToArray(downloadWebPage("http://api.ataxcloudapp.com/v1/franchise/listing/?location=" + zip))) {
offices.add(
new Office(
of,
backToArray(downloadWebPage("http://api.ataxcloudapp.com/v1/franchise/details/hours/" + of[0])).get(0),
downloadImage("https://www.ataxcloudapp.com/WebShared/uploads/franchises/" + of[0] + "/manager-photo.jpg?404=picture-placeholder.jpg"),
downloadImage("https://maps.googleapis.com/maps/api/staticmap?center=" + of[12] + ","+ of[13] +"&zoom=12&size=300x150&maptype=roadmap")
)
);
}
subscriber.onCompleted();
}
});
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
return offices;
}

上面的解决方案有点管用,加载结果需要很长时间,而且不一致。最后 3 个调用都取决于第一个调用中提供的信息。我在这里做错了什么?

最佳答案

首先,请注意,为了能够组合异步方法,它们都应该返回 Observable<Something>而不是直接Something .

所以你应该改变你的下载方式

public Observable<Image> downloadImage(String url)
public Observable<WebPage> downloadWebPage(String url)

或者如果您无法更改它们,则围绕它们创建包装器方法。

然后你可以使用flatMapzip对于 getOffices方法:

public Observable<Office> getOffices() {
return downloadWebPage("office-url")
.flatMap(new Func1<WebPage, Observable<Office>>() {
public Observable<Office> call(WebPage webPage) {
String url1 = "blah" + webPage.getInfo1();
String url2 = "blah" + webPage.getInfo2();
String url3 = "blah" + webPage.getInfo3();
return Observable.zip(
downloadWebPage(url1),
downloadImage(url2),
downloadImage(url3),
new Func3<WebPage, Image, Image, Office>() {
public Office call(WebPage p, Image img1, Image img2) {
return new Office(p.getInfo0(), img1, img2);
}
});
}
});
}

关于java - RxAndroid,结合多个网络调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29569905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com