Android Background Processing

Sep 23 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk 2021.2.1

Part 2: Use WorkManager in Complex Apps

10. Chain Work

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 09. Implement WorkManager in Complex Apps Next episode: 11. Challenge - WorkManager

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 10. Chain Work

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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

After building a worker, observing its status, and returning a result, you’re ready to build more workers, and chain them together! :]

@Serializable
class UploadResponse(val message: String = "", val url: String = "")
  @Multipart
  @POST("/files")
  suspend fun uploadImage(
      @Part imageFile: MultipartBody.Part
  ): UploadResponse
suspend fun uploadImage(file: File): UploadResponse {
  val part: MultipartBody.Part = MultipartBody.Part.createFormData("file", file.name, file.asRequestBody())

  return apiService.uploadImage(part)
}
class UploadImageWorker(context: Context, workerParameters: WorkerParameters) :
    CoroutineWorker(context, workerParameters) {

  override suspend fun doWork(): Result {

  }
}
class UploadImageWorker(context: Context, workerParameters: WorkerParameters) :
    CoroutineWorker(context, workerParameters) {

  private val remoteApi by lazy { App.remoteApi }

  override suspend fun doWork(): Result {
    val imagePath = inputData.getString("image_path") ?: return Result.failure()

    val result = remoteApi.uploadImage(File(imagePath))

    return if (result.message == "Success!") {
      Result.success()
    } else {
      Result.failure()
    }
  }
}
private const val NO_IMAGE = "noImage"

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

  override fun doWork(): Result {
    val imagePath = inputData.getString("image_path") ?: NO_IMAGE
    val parts = imagePath.split("/")

    if (imagePath.isBlank() || imagePath == NO_IMAGE) {
      val outputData = workDataOf("is_downloaded" to false)
      return Result.success(outputData)
    }

    val rootFile = applicationContext.externalMediaDirs.first()

    val lastSegment = parts.last()

    return try {
      val isDownloaded = rootFile.list()?.any { filePath -> lastSegment in filePath }
      val outputData = workDataOf("is_downloaded" to (isDownloaded ?: false))

      Result.success(outputData)
    } catch (error: Throwable) {
      error.printStackTrace()
      Result.failure()
    }
  }
}
val isAlreadyDownloaded = inputData.getBoolean("is_downloaded", false)
val imageDownloadPath = inputData.getString("image_path") ?: return Result.failure()
val parts = imageDownloadPath.split("/")

if (isAlreadyDownloaded) {
  val imageFile = File(applicationContext.externalMediaDirs.first(), parts.last())
  return Result.success(workDataOf("image_path" to imageFile.absolutePath))
}
val imageUrl = URL("$BASE_URL/files/$imageDownloadPath")

...

val file = File(applicationContext.externalMediaDirs.first(), parts.last())
val localImagePath = BASE_URL + "/files/${image.imagePath}"

Glide.with(containerView).load(localImagePath).into(containerView.image)
val localImageCheckWorker = OneTimeWorkRequestBuilder<LocalImageCheckWorker>()
    .setInputData(workDataOf("image_path" to imageUrl))
    .build()
        
val workManager = WorkManager.getInstance(requireActivity())
workManager.beginWith(localImageCheckWorker)
    .then(downloadImageWorker)
    .enqueue()
val context = activity as? Context ?: return
val selectedImage = data?.data ?: return
val fileUri = FileUtils
    .getImagePathFromInputStreamUri(selectedImage, context.contentResolver, context)

val worker = OneTimeWorkRequestBuilder<UploadImageWorker>()
    .setInputData(workDataOf("image_path" to fileUri))
    .build()

WorkManager.getInstance(requireActivity())
  .enqueue(worker)