我试图深入了解RxJava2世界的奇迹,但我仍然很困惑。 基本上我必须在用户点击按钮时调用API,因此我使用Retrofit2客户端返回一个Observable,我订阅了按钮的on click方法。
问题是,当点击按钮两次时,我会得到:
io.reactivex.exceptions.ProtocolViolationException: It is not allowed to subscribe with a(n) <package>.MainActivity$1 multiple times. Please create a fresh instance of <package>.MainActivity$1 and subscribe that to the target source instead.
如果我在onComplete之后处理观察者,则因为订阅失效而无法调用api ..我是否遗漏/误解了某些内容?
public class MainActivity extends AppCompatActivity {
@BindView(R.id.button) Button button;
private DisposableObserver<PopularGames[]> observer;
private Observable<PopularGames[]> popularGamesObservable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
APIsInterface apiClient = MyApplication.getInstance(this).getApiClient();
popularGamesObservable = apiClient.getPopularGames();
observer = new DisposableObserver<PopularGames[]>() {
@Override
public void onNext(PopularGames[] result) {
Timber.d("onNext " + Arrays.asList(result));
}
@Override
public void onError(Throwable e) {
Timber.e("onError " + e);
}
@Override
public void onComplete() {
Timber.d("onComplete");
}
};
}
@OnClick(R.id.button)
public void onViewClicked() {
popularGamesObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(observer);
}
}
答案 0 :(得分:1)
io.reactivex.exceptions.ProtocolViolationException
你能做什么
CompositeDisposable compositeDisposable = new CompositeDisposable();
然后
@OnClick(R.id.button)
public void onViewClicked() {
compositeDisposable.add( popularGamesObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<PopularGames[]>() {
@Override
public void onNext(PopularGames[] result) {
Timber.d("onNext " + Arrays.asList(result));
}
@Override
public void onError(Throwable e) {
Timber.e("onError " + e);
}
@Override
public void onComplete() {
Timber.d("onComplete");
}
}));
}
然后在onDestory
compositeDisposable.dispose();