如何使用retofit2和RxAndroid取消请求

时间:2015-12-10 10:42:03

标签: android retrofit rx-java rx-android

我正在使用Retrofit 2.0和Rx-android来加载我的API。我按照this site处的RxJava Integration with CallAdapter部分进行操作,效果很好。但是,我不知道如何使用可观察对象取消加载请求。请帮忙给我一个想法。

1 个答案:

答案 0 :(得分:17)

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

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

Subscription subscription = getObservable().subscribe();

//When you want to stop execution
subscription.unsubsribe();

您可以查看代码here。具体来说,这些行代码

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();
  }
}));