Android Workmanager: Implementation, Tips and Pitfalls to Avoid (1)
Tags: android, workmanager, kotlin
Published: 2023-02-07 17:19:23

For over a year i have been interacting with the android Workmanager Api . A very powerful api, I resolved to publish some articles around what I have been building and this is the first in the series. 

You have been presented with a situation. The business wants all interactions and flow happening in the app to happen offline and whenever the user's internet is turned on synchronise that data to the backend.  You do your research and you come across a powerful API in android called Workmanager and you start building.  The aim of this article is to give a short tutorial on workmanager as well as give tips on how to avoid potential catastrophic events that could lead to issues later on. 

Workmanager is fantastic when you want to schedule work to be done sometime in the future with some constraints. Take for example, in the example given above, the constraint is internet access. Workmanager gives you the ability to specify the conditions that should be met before your work begins.   

Let us declare a workmanager class called `ScoresAverageWorker` this class syncs all the attendance results taken by a teacher for their class. 

The first thing you want to do is to create the Workmanager Class



```
class ScoresAverageWorker(
    context: Context,
    workerParams: WorkerParameters
) : Worker(context, workerParameters) {

override fun doWork(): Result {
	 
if (work is successful) {
	 
return Result.success()
	 
} else {
	
 if (work needs to be retried) {
	 // try again if there is a server error
	
 return Result.retry()
	 }
 return Result.failure()
	 }
	 }
}

```

this class extends the Worker class and takes in two parameters, which are context and worker parameters.   Worker parameters refer to data you might need to do work. we will talk about it later, for now let us focus on other aspects.  

The above class overrides a function called doWork and that is where the work we would like workmanager to perform gets done. [This function returns a Class Result](https://developer.android.com/reference/androidx/work/ListenableWorker.Result#Result()) 

The three different methods you can return from the class are Result.success() , which indicates that the work was successful. Result.failure() which indicates that the work was not successful and Result.retry() which tells Workmanager to retry the work. 

Now that we are done setting up the workmanager class. we can now move ahead to figuring out how to instantiate it.   You can determine how periodically you want your work to occur, either once or at intervals. 

In this article, we would stick to only one-time work requests.  To start a one-time work, we need to first instantiate our workmanager class, then use OneTimeWorkRequestBuilder to build our request.  

```
val workManager = WorkManager.getInstance(this)

val scoresAverageWorker: OneTimeWorkRequest =
    OneTimeWorkRequestBuilder<ScoresAverageWorker>()
        .setInitialDelay(5, TimeUnit.SECONDS)
        .build()


workManager.beginUniqueWork("Unique_Work_Name", ExistingWorkPolicy.REPLACE, scoresAverageWorker).enqueue()

```

The above code instantiates a one-time work request builder, sets an initial delay of 5 seconds to it and begins a unique work. 

The second part of this series will focus on how to send data to our workmanager class and how to create a coroutine worker.