Threading in RxWorker
Stay organized with collections
Save and categorize content based on your preferences.
We provide interoperability between WorkManager and RxJava. To get started,
include work-rxjava3
dependency in addition to work-runtime
in your gradle file.
There is also a work-rxjava2
dependency that supports rxjava2 instead.
Then, instead of extending Worker
, you should extendRxWorker
. Finally
override the RxWorker.createWork()
method to return a Single<Result>
indicating the Result
of your execution, as
follows:
Kotlin
class RxDownloadWorker(
context: Context,
params: WorkerParameters
) : RxWorker(context, params) {
override fun createWork(): Single<Result> {
return Observable.range(0, 100)
.flatMap { download("https://www.example.com") }
.toList()
.map { Result.success() }
}
}
Java
public class RxDownloadWorker extends RxWorker {
public RxDownloadWorker(Context context, WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Single<Result> createWork() {
return Observable.range(0, 100)
.flatMap { download("https://www.example.com") }
.toList()
.map { Result.success() };
}
}
Note that RxWorker.createWork()
is called on the main thread, but the return
value is subscribed on a background thread by default. You can override RxWorker.getBackgroundScheduler()
to change the
subscribing thread.
When an RxWorker
is onStopped()
, the subscription will get disposed of, so
you don't need to handle work stoppages in any special way.
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2024-01-03 UTC.
[{
"type": "thumb-down",
"id": "missingTheInformationINeed",
"label":"Missing the information I need"
},{
"type": "thumb-down",
"id": "tooComplicatedTooManySteps",
"label":"Too complicated / too many steps"
},{
"type": "thumb-down",
"id": "outOfDate",
"label":"Out of date"
},{
"type": "thumb-down",
"id": "samplesCodeIssue",
"label":"Samples / code issue"
},{
"type": "thumb-down",
"id": "otherDown",
"label":"Other"
}]
[{
"type": "thumb-up",
"id": "easyToUnderstand",
"label":"Easy to understand"
},{
"type": "thumb-up",
"id": "solvedMyProblem",
"label":"Solved my problem"
},{
"type": "thumb-up",
"id": "otherUp",
"label":"Other"
}]
{"lastModified": "Last updated 2024-01-03 UTC."}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-01-03 UTC."]]