Android Retrofit+RxJava 取消网络请求

可以通过Observer监听的onSubscribe回调方法中取得Disposable,然后通过Disposable对象来取消请求。

实例代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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();
}
}

Click and drag to move