krupal.agile
krupal.agile

Reputation: 815

How to cancel individual network request in Retrofit with RxJava?

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?

Upvotes: 2

Views: 549

Answers (1)

akarnokd
akarnokd

Reputation: 70017

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

Upvotes: 3

Related Questions