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?
I think you should not use
WorkManagerto make a regular network request, e.g., fetching data, calling an API, etc. Because: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