Synchronous or Asynchronous Rxjava inside the Worker (from WorkManager component) what's the right choice?
Since WorkManager version 1.0.0-alpha12
they added a new artifact called work-rxjava2
that includes RxWorker
class exactly for this purpose. It is a special case of ListenableWorker
expecting Single<Result>
.
To implement it, first make sure you include correct artifacts to your build.gradle
:
dependencies {
...
implementation "android.arch.work:work-runtime-ktx:$work_version"
implementation "android.arch.work:work-rxjava2:$work_version"
}
And implement your RxWorker
:
class MyRxWorker(context : Context, params : WorkerParameters) : RxWorker(context, params) {
val remoteService = RemoteService()
override fun createWork(): Single<Result> {
return remoteService.getMySingleResponse()
.doOnSuccess { /* process result somehow */ }
.map { Result.success() }
.onErrorReturn { Result.failure() }
}
}
Edit: WorkManager now officially supports an RxWorker
. Take a look at the answer above for more information.
doWork
happens on a background thread. So it's safe to block. You should wait for the Observable
to complete before you return a Result
.
We are also working on making this easier with asynchronous APIs. Stay tuned.