How to cancel individual network request in Retrofit with RxJava?

允我心安 提交于 2019-12-12 10:09:12

问题


I am downloading some files from the network using retrofit and 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. How do I cancel particular request?


回答1:


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


来源:https://stackoverflow.com/questions/47844512/how-to-cancel-individual-network-request-in-retrofit-with-rxjava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!