1

So i have a disposable in my classe declared like this : private var disposable = Disposables.disposed() And i use it like this :

 disposable = fileDownloader.download()
                .toFlowable(BackpressureStrategy.LATEST)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({dosomething},
                          {handle error},
                          {onComplete })

Basically it download a file and the fonction download return an Observable. It work perfectly fine, my file is downloaded and i handle error and onComplet. My problem is that i use this fonction in a library classe and not an activity. so i don't know how to cancel my disposable. When i used disposable in classe i could do this :

override fun onDestroy() {
    super.onDestroy()
    disposable.dispose()
}

And it would stop my disposable. But i don't know how to handle it outside an activity. I tried to add a methode in my library doing this :

fun cancelDownload(){
        println("cancelDownload")
        disposable.dispose()
    }

And call it when my activity onDestroyed is called, i get the "cancelDownload" printed but my disposable is not stoped. what i want to achieve is: when i quit my download activity, the download disposable is canceled. Am i missing something ? or how can I manage to do it ?

EDIT

As someone suggested i was using downloading multiples files and so i had multiples disposable and it's why i couldn't dispose. so i added a private val disposables = CompositeDisposable() to hold my disposable. so i made my disposable a val and i added it after the use : disposables.add(disposable) and i changed my cancel fonction to this :

fun cancelDownload(){
        println("cancelDownload")
        disposables.dispose()
    }

Problem is that it's still don't work, when i quit the download activity, i got "cancelDownload" printed but the download continue. Also when i clear data and try to redownload after, the download doesn't start. Look like my disposable is not created again.

EDIT2

It's seem that disposables.dispose() is a kind of hard clear where we are no longer able to subscribe anything to the observable so i used disposables.clear() instead and it just remove the observers as i wanted so it worked.

XCarb
  • 735
  • 10
  • 31
  • 1
    Are you calling `dispose()` on exactly the same disposable you got from `subscribe()`? For example if you call that download function many times it will overwrite whatever you had in `disposable` before. – laalto Feb 04 '22 at 13:54
  • Ho i tried it and effectively i was doing multiple download and it's why it doesn't work, do you have anyway to fix this ? – XCarb Feb 04 '22 at 14:39

0 Answers0