[英]How to cancel individual network request in Retrofit with RxJava?
I am downloading some files from the network using retrofit and rxjava. 我正在使用翻新和rxjava从网络下载一些文件。 In my app, the user may cancel the download. 在我的应用中,用户可以取消下载。
Pseudo Code: 伪代码:
Subscription subscription = Observable.from(urls)
.concatMap(this::downloadFile)
.subscribe(file -> addFileToUI(file), Throwable::printStackTrace);
Now, If I unsubscribe this subscription, then all requests get canceled. 现在,如果我取消订阅此订阅,那么所有请求都会被取消。 I want to download one by one, that's why used concatMap. 我要一一下载,这就是为什么要使用concatMap的原因。 How do I cancel particular request? 如何取消特定请求?
There is a mechanism to cancel individual flows by external stimulus: takeUntil
. 有一种机制可以通过外部刺激来取消个人流量: 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.