How to use work request chaining on Periodic Work Request in work Manager in kotlin

Viewed 72

I have three work request as below

 val imageWorker = OneTimeWorkRequestBuilder<ImageUploadingWorker>()
            .setConstraints(constraints)
            .addTag("imageWork")
            .build()

        val gpSurveyWorker = OneTimeWorkRequestBuilder<GpSurveyUploadingWorker>()
            .setConstraints(constraints)
            .addTag("gpSurveyWork")
            .build()

        val gpSurveyListWorker = OneTimeWorkRequestBuilder<SurveyListUpdateWorker>()
            .setConstraints(constraints)
            .addTag("gpSurveyList")
  

      .build()

and I enqueue them in work Manager as

 workManager.beginWith(imageWorker)
            .then(gpSurveyWorker)
            .then(gpSurveyListWorker)
            .enqueue()

And this work perfectly, but I want periodic work request that executes after every 4 hours, I can not schedule them individually because each request depends on the previous request. And I need it periodically because it syncs my offline data to the server. I read that chaining is not possible in periodic work requests, so in this case, is there any way to create the first request as periodic and the other request are executed after the first request.

Please help me in creating chaining of these work requests.

Thanks in advance.

1 Answers

If you want to chain some periodic work requests then the best way as per my knowledge is to first create a periodic work request and in the worker class inside the doWork() method just put aa the three or four requests and make them one Time request.

What happens in this situation is your first request(Periodic Work Request) will execute all the rest three requests (which are one-time requests).

In this way, you can achieve chaining of periodic work requests.

Related