Notes: 05. Challenge - Workers
The student materials have been reviewed and are updated as of SEPTEMBER 2022.
To master using the WorkManager API, before implementing it in a more complex application, you first have to solve a fun challenge! :] In this challenge you have to build a worker to apply a sepia filter to your bitmap. Here’s a hint: the Sepia Filter code is prepared for you, in the ImageUtils class!
That’s it! Now pause the video and solve the challenge, using everything you’ve learned so far! Then after you’re done, unpause the video and compare the two solutions. Good luck!
First create a new worker class called SepiaFilterWorker.kt, and override the doWork() function:
class SepiaFilterWorker(context: Context, workerParameters: WorkerParameters) :
Worker(context, workerParameters) {
override fun doWork(): Result {
}
}
Just like before, you’re creating a worker. This worker should take in the imagePath for the downloaded image file, apply a sepia filter to the bitmap, and save the file again.
To do that, add the following code:
class SepiaFilterWorker(context: Context, workerParameters: WorkerParameters) :
Worker(context, workerParameters) {
override fun doWork(): Result {
val imagePath = inputData.getString("image_path") ?: return Result.failure()
val bitmap = BitmapFactory.decodeFile(imagePath)
val newBitmap = ImageUtils.applySepiaFilter(bitmap)
val outputStream = FileOutputStream(imagePath)
outputStream.use { output ->
newBitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
output.flush()
}
val output = workDataOf("image_path" to imagePath)
return Result.success(output)
}
}
Using ImageUtils you’re applying the sepia filter to a bitmap. You then proceed to use a FileOutputStream to save the new filtered bitmap to a file.
Finally, you return the same image path for the image, to be able to display the image in the app.
Now head over to the MainActivity.kt, and add the final worker to the queue:
val sepiaFilterWorker = OneTimeWorkRequestBuilder<SepiaFilterWorker>()
.setConstraints(constraints)
.build()
workManager.beginWith(clearFilesRequest)
.then(downloadRequest)
.then(sepiaFilterWorker)
.enqueue()
And instead of observing the downloadRequest, observe the sepia filter request:
workManager.getWorkInfoByIdLiveData(sepiaFilterWorker.id)
That’s all you have to do! :] Now run the project to verify your work!
Great job! You’ve finished this challenge, and this part of the course! Way to go! :]