我正在为我的应用程序开发网络功能。因此,我决定尝试使用Square的Retrofit。我看到他们支持简单的Callback
。
@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
和 RxJava 的 Observable
@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);
Both look pretty similar at first glance, but when it gets to implementation it gets interesting...
在第一眼看上去,两者看起来非常相似,但是当涉及到实现时就变得有趣了...
而使用简单的回调实现将类似于这样:
api.getUserPhoto(photoId, new Callback<Photo>() {
@Override
public void onSuccess() {
}
});
这很简单明了。但是使用Observable
会很冗长且相当复杂。
public Observable<Photo> getUserPhoto(final int photoId) {
return Observable.create(new Observable.OnSubscribeFunc<Photo>() {
@Override
public Subscription onSubscribe(Observer<? super Photo> observer) {
try {
observer.onNext(api.getUserPhoto(photoId));
observer.onCompleted();
} catch (Exception e) {
observer.onError(e);
}
return Subscriptions.empty();
}
}).subscribeOn(Schedulers.threadPoolForIO());
}
而这还不是全部。你仍然需要像这样做:
Observable.from(photoIdArray)
.mapMany(new Func1<String, Observable<Photo>>() {
@Override
public Observable<Photo> call(Integer s) {
return getUserPhoto(s);
}
})
.subscribeOn(Schedulers.threadPoolForIO())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Photo>() {
@Override
public void call(Photo photo) {
//save photo?
}
});
我有什么遗漏吗?或者使用Observable
是错误的情况?
何时应该优先选择Observable
而不是简单的回调函数?
更新
如@Niels在他的答案中所示或在Jake Wharton的示例项目U2020中,使用retrofit比上面的示例要简单得多。 但是基本问题仍然是相同的-何时应该使用其中一种方法?