Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Expect a Result From Workers

The student materials have been reviewed and are updated as of SEPTEMBER 2022.

Use the WorkManager API to implement a simple worker which does some work in the background.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Now that you know how to implement a Worker, it’s time to implement another one, add results to your workers, and chain them together! Let’s see how to do so! :]

class FileClearWorker(context: Context, workerParameters: WorkerParameters) :
    Worker(context, workerParameters) {

  override fun doWork(): Result {
    val root = applicationContext.externalMediaDirs.first()

    return try {
      root.listFiles()?.forEach { child ->
        if (child.isDirectory) {
          child.deleteRecursively()
        } else {
          child.delete()
        }
      }

      Result.success()
    } catch (error: Throwable) {
      error.printStackTrace()
      Result.failure()
    }
  }
}
val imagePath = "owl_image_${System.currentTimeMillis()}.jpg"
val inputStream = connection.inputStream
val file = File(applicationContext.externalMediaDirs.first(), imagePath)

...

val output = workDataOf("image_path" to file.absolutePath)
return Result.success(output)
val clearFilesRequest = OneTimeWorkRequestBuilder<FileClearWorker>()
    .build()
val clearFilesRequest = OneTimeWorkRequestBuilder<FileClearWorker>()
    .build()

val downloadRequest = OneTimeWorkRequestBuilder<DownloadWorker>()
    .setConstraints(constraints)
    .build()

val workManager = WorkManager.getInstance(this)

workManager.beginWith(clearFilesRequest)
.then(downloadRequest)
.enqueue()
val imagePath = info.outputData.getString("image_path")

if (!imagePath.isNullOrEmpty()) {
  displayImage(imagePath)
}

Reviews

Comments