如何使用RxJava在Retrofit中取消单个网络请求? [英] How to cancel individual network request in Retrofit with RxJava?

查看:1027
本文介绍了如何使用RxJava在Retrofit中取消单个网络请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用retrofit和rxjava从网络下载一些文件。在我的应用程序中,用户可以取消下载。

I am downloading some files from the network using retrofit and rxjava. In my app, the user may cancel the download.

伪代码:

   Subscription subscription = Observable.from(urls)
            .concatMap(this::downloadFile)
            .subscribe(file -> addFileToUI(file), Throwable::printStackTrace);

现在,如果我取消订阅此订阅,则所有请求都会被取消。我想逐个下载,这就是使用concatMap的原因。如何取消特定请求?

Now, If I unsubscribe this subscription, then all requests get canceled. I want to download one by one, that's why used concatMap. How do I cancel particular request?

推荐答案

有一种机制可以通过外部刺激取消个别流量: takeUntil 。你必须使用一些外部跟踪:

There is a mechanism to cancel individual flows by external stimulus: takeUntil. You have to use some external tracking for it though:

ConcurrentHashMap<String, PublishSubject<Void>> map =
     new ConcurrentHashMap<>();


Observable.from(urls)
.concatMap(url -> {
    PublishSubject<Void> subject = PublishSubject.create();
    if (map.putIfAbsent(url, subject) == null) {
        return downloadFile(url)
            .takeUntil(subject)
            .doAfterTerminate(() -> map.remove(url))
            .doOnUnsubscribe(() -> map.remove(url));
    }
    return Observable.empty();
})
.subscribe(file -> addFileToUI(file), Throwable::printStackTrace);

// sometime later

PublishSubject<Void> ps = map.putIfAbsent("someurl", PublishSubject.create());
ps.onCompleted();

这篇关于如何使用RxJava在Retrofit中取消单个网络请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆