How to create a common worker when using WorkManager?

66 Views Asked by At

I want to create a NetworkRequestWorker which executes a network request using WorkManager.

All network requests would have a similar set of logic:

  • Parameters for network request (request body)
  • Do something when request succeeds
  • Do something when request fails

I want to abstract this functionality out so we can use same worker for making a network request.

Since you can't pass parameters to a CoroutineWorker I am not sure what would be the best way to abstract this out.

Also, a Worker can only take in primitive data types, one option is to serialize a class and pass it to the worker but I am thinking there might be better ways to achieve this.

Another option would be to create a new Worker class for each network request but that would lead to code duplication.

Google's nowinandroid sample passes repositories to a worker, does that mean we can passes classes as a parameter. How do we pass an object to worker?

1

There are 1 best solutions below

0
fshdn19 On

I think you should not use WorkManager to make a regular network request, e.g., fetching data, calling an API, etc. Because:

  • It's difficult to control progress
  • It's difficult to handle errors or get the response
  • And the more important thing is you cannot ensure that your network request is executed immediately

You can execute a regular network request directly in your viewmodel or in your activity, fragment with coroutines and/or Retrofit. It's quietly simple and easy to control.

For example, with coroutine, you can see it here