Expert wanna be
Expert wanna be

Reputation: 10624

RxJava, What happened if I don't call dispose?

My Android app needs to support to upload a big file, but I do not want a user wait until the upload is completed.

Usually, when I use Observable, I call dispose() for it when the view is destroyed.

But in uploading case, I can not dispose it in any case until it finished.

So I was thinking to try to like this,

private val compositeDisposable: CompositeDisposable = CompositeDisposable()

fun upload() {
    val disposable = Observable.just(true).delay(20, TimeUnit.SECONDS).subscribe({
        Log.d("=>", "Upload finished")
        disposeUploader()
    })  

    compositeDisposable.add(disposable)
}

fun disposeUploader() {
    compositeDisposable.clear()
    compositeDisposable.dispose()
}

But the problem is the upload() could be called multiple times, so the first uploader will dispose of all other processing calls.

What happened if I don't call dispose? or is there any way dispose of itself when it is completed?

Upvotes: 7

Views: 7569

Answers (1)

yosriz
yosriz

Reputation: 10267

The idea of disposing an Observable serves two purposes:

1) Avoid memory leaks - detach view references that might be held by ongoing request module.
2) Release resources - stop ongoing background task to free unneeded resources, when the user exit your activity for instance, a request/processing might not be relevant anymore, so no point to keep it running.

In your case you want your background task (uploading file) to resume, avoiding (2), while having your view detaching from it (1).

Your solution of disposing after some period of time miss the point as Observable will dispose itself at completion. moreover, you can't assume a specific duration for the upload (at most it is timeout value).

The solution with RxJava is multicasting your Observable using operator like publish and share, in your case:

val multicastedObservable = uploadObservable.publish()
            .autoConnect()
            .subscriber(//your view related subscriber);

This way, uploadObservable will start execute at first subscribe but will not stop when dispose is called, but rather will detach the reference to view.


Having said all that, it's worth noting that your upload scenario cannot be done reliably without foreground service in Android.

Upvotes: 14

Related Questions