override fun doWork(): Result { // do something! return Result.success() } } val constraints = Constraints.Builder().build() val request = OneTimeWorkRequest.Builder(MyWorker::class.java) .setConstraints(constraints) .build() WorkManager.getInstance().enqueue(request)
-> // Store in WorkManager DB workDatabase.workSpecDao().insertWorkSpec(...) workDatabase.dependencyDao().insertDependency(...) workDatabase.workTagDao().insert(...) workDatabase.workNameDao().insert(...) -> scheduleWorkInBackground() After force-stop, reschedule!!
ListenableFuture<Result> startWork(); public abstract static class Result { ... } } public abstract class Worker extends ListenableWorker { @WorkerThread public abstract @NonNull Result doWork(); } public abstract class RxWorker extends ListenableWorker { @MainThread public abstract Single<Result> createWork(); } abstract class CoroutineWorker(...) : ListenableWorker(...) { abstract suspend fun doWork(): Result } work-runtime work-rxjava2 work-runtime-ktx
fun doWork(): Result { return Result.success() } } @Test fun testCoroutineWorkerTest() { runBlocking { val worker = TestListenableWorkerBuilder<TestWorker>(context) .setInputData(workDataOf("key" to 10)) .setRunAttempCount(2) .build() val result = worker.startWork().await() assertThat(result).isEqualTo(Result.success()) } }
doWork(): Result { return Result.success() } } @Test fun testWorkerTest() { runBlocking { val executor = Executors.newSingleThreadExecutor() val worker = TestWorkerBuilder<TestWorker>(context, executor) .setInputData(workDataOf("key" to 10)) .setRunAttempCount(2) .build() val result = worker.startWork().await() assertThat(result).isEqualTo(Result.success()) } }
workInfo: WorkInfo? -> if (workInfo != null) { val progress = workInfo.progress val value = progress.getInt(PROGRESS, 0) // Do something with progress information } }) Worker Progress