如何使用retofit2和RxAndroid取消请求

Ngu*_*inh 7 android rx-java retrofit rx-android

我正在使用Retrofit 2.0和Rx-android来加载我的API.我按照这个网站的部分RxJava Integration with CallAdapter,它工作正常.但是,我不知道如何使用可观察对象取消加载请求.请帮忙给我一个主意.

Vas*_*tur 17

取消RxJava Observable执行的唯一方法 - 取消订阅它.RxJavaCallAdapter将取消委托给okhttp客户端.

所以,你这么简单就像这样:

Subscription subscription = getObservable().subscribe();

//When you want to stop execution
subscription.unsubsribe();
Run Code Online (Sandbox Code Playgroud)

你可以在这里查看代码.具体来说,如果代码这些行

final Call<T> call = originalCall.clone();

// Attempt to cancel the call if it is still in-flight on unsubscription.
subscriber.add(Subscriptions.create(new Action0() {
  @Override public void call() {
    call.cancel();
  }
}));
Run Code Online (Sandbox Code Playgroud)