【问题标题】:How to cancel request with retofit2 and RxAndroid如何使用 retofit2 和 RxAndroid 取消请求
【发布时间】:2016-03-15 23:07:10
【问题描述】:

我正在使用 Retrofit 2.0 和 Rx-android 来加载我的 API。我在this site 关注RxJava Integration with CallAdapter 部分,它工作正常。但是,我不知道如何使用可观察对象取消加载请求。请帮忙给我一个想法。

【问题讨论】:

    标签: android retrofit rx-java rx-android


    【解决方案1】:

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

    【讨论】:

    • 我只是测试了 'unsubsribe()' 并查看它是否有效。订阅者将不再被调用。但是为什么 okhttp continue 会多次打印日志。如何检查 okhttp 是否会被取消?
    • 我也检查过了,它工作正常,简单打印 GET 和 END GET。但是当然没有任何请求可以被阻止。可能是你在这种情况下。但它仍然是取消请求的唯一方法,它与 Retrofit Call cancel 完全一样。您可以通过将断点设置为 call.cancel(); 来检查它。例如
    • 谢谢你,瓦西洛夫。由于这是唯一的方法,我会一直使用它,直到找到更好的解决方案
    • @VasilovArtur 源代码链接已损坏。这是最新的链接github.com/square/retrofit/blob/master/retrofit-adapters/rxjava/… 并且它不包含您提供的代码sn-p。
    • @toobsco42 实际上什么都没有改变。取消订阅时通话仍然取消,现在在这里github.com/square/retrofit/blob/master/retrofit-adapters/rxjava/…
    猜你喜欢
    • 2019-04-24
    • 2011-10-15
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    相关资源
    最近更新 更多