3

I have a network change notifier class based on ConnectivityManager.NetworkCallback and i want to update some fields when network is available;

override fun onAvailable(network: Network?) {
    super.onAvailable(network)
val db = StoreDatabase.getInstance(context)
val stores = db.createStores()

val disposable = stores.insertStore(Stores(storeName = "testOnAvailableNetInsertions", status 
= AppConstants.Database.SYNC_FAIL))
        .subscribeOn(Schedulers.io())
        .observeOn(Schedulers.io()).subscribeWith(object : DisposableCompletableObserver() {
            override fun onComplete() {
                 if (!isDisposed)
                dispose()
            }

            override fun onError(e: Throwable) {
                if (!isDisposed)
                    dispose()
            }

        }).dispose()

Is it okay to call dispose at the end of the method, or do i have to dispose that variable somewhere else, and this is my Dao;

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertStore(stores: Stores): Completable 
Manoj Perumarath
  • 9,337
  • 8
  • 56
  • 77

1 Answers1

1

Note that you do not need to explicitly dispose subscriptions after onComplete or onError is called. Observers will be unsubscribed once they receive any termination events. So one thing you can try is this:

super.onAvailable(network)
val db = StoreDatabase.getInstance(context)
val stores = db.createStores()

stores.insertStore(Stores(storeName="testOnAvailableNetInsertions",
        status=AppConstants.Database.SYNC_FAIL))
    .subscribeOn(Schedulers.io())
    .subscribe()

Calling .dispose() at the end of the chain will dispose the subscription immediately and it doesn't make much sense in most of the scenarios. It might just work in your case since your subscriber technically doesn't do much, but I am not sure. Also, .dispose() does not return anything. In Kotlin it will return a Unit so the val disposable will just be a Unit.

Sanlok Lee
  • 3,404
  • 2
  • 15
  • 25
  • If so, then why we are clearing/disposing disposables on onDestroy, feels akward with this thing. – Manoj Perumarath Feb 28 '19 at 08:06
  • @Manoj Perumarath, we need to explicitly clear disposables in the view layer because there is no guarantee that all observables will complete before the view gets destroyed. – Sanlok Lee Feb 28 '19 at 08:44
  • Imagine having a subscriber not cleared even after `onDestroy` and trying to update the view that is already destroyed in its `onNext` call. – Sanlok Lee Feb 28 '19 at 08:48