【发布时间】:2016-06-27 09:21:52
【问题描述】:
我有一个 Observable<<List<Foo>> getFoo(),它是从改造服务创建的,并且在调用
.getFoo() 方法,我需要与多个订阅者共享它。但是调用.share() 方法会导致重新执行网络调用。重播运算符也不起作用。我知道一个潜在的解决方案可能是.cache(),但我不知道为什么会导致这种行为。
// Create an instance of our GitHub API interface.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
// Create a call instance for looking up Retrofit contributors.
Observable<List<Contributor>> testObservable = retrofit
.create(GitHub.class)
.contributors("square", "retrofit")
.share();
Subscription subscription1 = testObservable
.subscribe(new Subscriber<List<Contributor>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onNext(List<Contributor> contributors) {
System.out.println(contributors);
}
});
Subscription subscription2 = testObservable
.subscribe(new Subscriber<List<Contributor>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onNext(List<Contributor> contributors) {
System.out.println(contributors + " -> 2");
}
});
subscription1.unsubscribe();
subscription2.unsubscribe();
上面的代码可以重现上述行为。可以调试一下,看到收到的Lists属于不同的MemoryAddress。
我也将 ConnectableObservables 视为一种潜在的解决方案,但这需要我随身携带原始的 observable,并且每次我想添加新的订阅者时都调用 .connect()。
.share() 的这种行为在 Retrofit 1.9 之前运行良好。它停止在 Retrofit 2 - beta 上工作。我还没有使用几小时前发布的 Retrofit 2 发布版本对其进行测试。
编辑:2017 年 1 月 2 日
为了以后的读者,我写了一篇文章here详细解释这个案例!
【问题讨论】: