K.Os
K.Os

Reputation: 5506

How to properly clear/dispose Disposable which periodically performs Completable?

I have a disposable which in some time interval performs request to the API

   val disposable =
    Flowable.interval(0, UPDATE_INTERVAL, TimeUnit.MILLISECONDS)
        .map {
          someRepository.sync(id)
              .doOnSubscribe { disposables?.add(it) }
              .subscribe()
        }
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnError { Timber.e(it, "Unable to sync") }
        .subscribe()
disposables?.add(disposable)

I am trying to clear it inside the onBackPressed method:

override fun onBackPressed() {
  super.onBackPressed()
  disposables?.dispose()
}

However it is not cleared and I see in the Android Studio Profiler that it is still performing this Flowable after I've clicked the back button.

What I am doing wrong?

UPDATE:

When i change map operator to flatMap as akarnokd suggested:

Error:(160, 11) Type inference failed: fun <R : Any!> flatMap(p0: 
((Long) -> Publisher<out R!>!)!, p1: Int): Flowable<R!>!
cannot be applied to
((Long) -> Completable,Int)

Upvotes: 0

Views: 3023

Answers (1)

akarnokd
akarnokd

Reputation: 70017

First of all, you are subscribing in a handler instead of using flatMap/concatMap:

val disposable =
Flowable.interval(0, UPDATE_INTERVAL, TimeUnit.MILLISECONDS, Schedulers.io())
    .onBackpressureDrop()
    .flatMapCompletable ({ someRepository.sync(id) }, 1)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ }, { Timber.e(it, "Unable to sync") })

disposables.add(disposable)

override fun onBackPressed() {
    super.onBackPressed()
    disposables.clear()
}

2) you can specify the thread of interval. 3) .subscribeOn(Schedulers.io()) has no effect as interval emits on its own thread. 4) doOnError is not error handling but only error peeking. An error would still crash your flow/app. 5) disposables.clear() is usually a better call to cleanup running flows so that you can reuse the same disposables next time.

I see in the Android Studio Profiler that it is still performing

Even though awkward, your original setup should have stopped on dispose(). My best guess is that disposables?.add doesn't execute because disposables is or becomes null at some point.

Upvotes: 1

Related Questions