I am a little bit confused on whether I should use WorkManager
API provided by android or the ExecutorService
which is a library by java.
I am working on a MVVM java android projects and i should perform async tasks to my database and i don't know which API to use. I did some research but no one compares them. Some of the tutorials use JobManager
to do async calls and other use Executors
.
So my question is can someone explain the difference between these two APIs and what are their use cases?
Thanks!
First, you need to read this:
https://developer.android.com/guide/background
Also now the new trend is not to use Threads, but Coroutines. So not an Executor, but a Coroutine.
Also in Android, the application can be killed at any time. Here you can see how it is less likely to be killed:
https://developer.android.com/guide/components/activities/process-lifecycle
Basically, if the user is not interacting with the application you might be killed.
So the question is:
Do you care if the task is finished if the user is interacting or not. If the end result is to show something to the user - you do not care if the app dies. So go with Coroutines.
If you want to be sure that the task is finished you need to keep the app alive. Historically this was done via a Service. But now there is no need to create one on your own. Just use the WorkManager and it will create one for you.
Basically, the idea of the WorkManager is to incorporate all APIs that you need to use like:
So the idea is for you to say:
I want this task to be finished for sure. Do it only on Wi-Fi and when the user is charging his phone.
You can say that you observe changes in the images, or other resources like SMS, contacts, etc. You can say that the work could be periodic, you can chain works, etc.
Basically the WorkManager is a complex thing.