Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WorkManager beginUniqueWork doesn't work as expected

Currently, I'm using WorkManager 1.0.0-alpha02.

def work_version = "1.0.0-alpha02"
implementation "android.arch.work:work-runtime:$work_version" // use -ktx for Kotlin
// optional - Firebase JobDispatcher support
implementation "android.arch.work:work-firebase:$work_version"

I have no problem to execute background worker, by using the following code, when the app quit.

Use enqueue, work as expected

OneTimeWorkRequest oneTimeWorkRequest =
        new OneTimeWorkRequest.Builder(SyncWorker.class)
                .addTag(SyncWorker.TAG)
                .build();

WorkManager workManager = WorkManager.getInstance();

workManager.enqueue(oneTimeWorkRequest);

Since, I would like to avoid more than one SyncWorker running at the same time. I try to use

Use beginUniqueWork, doesn't work

OneTimeWorkRequest oneTimeWorkRequest =
        new OneTimeWorkRequest.Builder(SyncWorker.class)
                .addTag(SyncWorker.TAG)
                .build();

WorkManager workManager = WorkManager.getInstance();

workManager.beginUniqueWork(
        SyncWorker.TAG,
        ExistingWorkPolicy.REPLACE,
        oneTimeWorkRequest
);

SyncWorker is not running at all.

May I know what step I had missed out? Thank you.

like image 779
Cheok Yan Cheng Avatar asked Jun 02 '18 13:06

Cheok Yan Cheng


1 Answers

beginUniqueWork() returns a WorkContinuation object. You need to call enqueue on that WorkContinuation to actually enqueue it with WorkManager:

workManager.beginUniqueWork(
    SyncWorker.TAG,
    ExistingWorkPolicy.REPLACE,
    oneTimeWorkRequest
).enqueue();
like image 196
ianhanniballake Avatar answered Sep 21 '22 08:09

ianhanniballake