How to dispose Rx in WorkManager?

  • Yes WorkManager is a good solution(even could be the best one)
  • You should use RxWorker instead of Worker. here is an example:

    1. To implement it. add androidx.work:work-rxjava2:$work_version to your build.gradle file as dependency.

    2. Extend your class from RxWorker class, then override createWork() function.

class TaskAlarmWorker(context: Context, params: WorkerParameters) :
    RxWorker(context, params), KoinComponent {

    private val daoRepository: DaoRepository by inject()  

    override fun createWork(): Single<Result> {
        Timber.d("doRxWork")

     return daoRepository.getTaskDao().getAllTasks()
                .doOnSuccess { /* process result somehow */ }
                .map { Result.success() }
                .onErrorReturn { Result.failure() }          

    }

}

Important notes about RxWorker:

  • The createWork() method is called on the main thread but returned single is subscribed on the background thread.
  • You don’t need to worry about disposing the Observer since RxWorker will dispose it automatically when the work stops.
  • Both returning Single with the value Result.failure() and single with an error will cause the worker to enter the failed state.
  • You can override onStopped function to do more.

Read more :

  • How to use WorkManager with RxJava
  • Stackoverflow answer