Threading in RxWorker

We provide interoperability between WorkManager and RxJava2. To get started, include work-rxjava2 dependency in addition to work-runtime in your gradle file. Then, instead of extending Worker, you should extend RxWorker. Finally override the RxWorker.createWork() method to return a Single<Result> indicating the Result of your execution, as follows:

public class RxDownloadWorker extends RxWorker {

    public NetworkOperationsWorker(Context context, WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Single<Result> createWork() {
        return Observable.range(0, 100)
            .flatMap { download("https://www.google.com") }
            .toList()
            .map { return 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.

Stopping an RxWorker will dispose the Observers properly, so you don't need to handle work stoppages in any special way.