Android Retrofit+RxJava 取消网络请求
可以通过Observer监听的onSubscribe回调方法中取得Disposable,然后通过Disposable对象来取消请求。
实例代码如下
private Disposable loginDisposable;
public void request() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl("http://www.yeyuanxinyi.com/YeYuanXinYi")
.build();
HttpService service = retrofit.create(HttpService.class);
Observable<Account> observable = service.login("yeyuanxinyi", "123456");
observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Account>() {
@Override
public void onSubscribe(Disposable d) {
// 在这里保存Disposable对象
loginDisposable = d;
}
@Override
public void onNext(Account t) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
// 取消请求
private void cancelLogin() {
if (loginDisposable != null && !loginDisposable.isDisposed()) {
loginDisposable.dispose();
}
}