Skip to content

Instantly share code, notes, and snippets.

@akueisara
Forked from ceruleanotter/UploadWorker.kt
Last active June 25, 2022 06:35
Show Gist options
  • Save akueisara/e44e5f1b67f5cf9872e1f1eda56a62c4 to your computer and use it in GitHub Desktop.
Save akueisara/e44e5f1b67f5cf9872e1f1eda56a62c4 to your computer and use it in GitHub Desktop.
WorkManager Basics - UploadWorker.kt Example
class UploadWorker(appContext: Context, workerParams: WorkerParameters)
: Worker(appContext, workerParams) {
override fun doWork(): Result {
try {
// Get the input, where this inputData is set when building the WorkRequest
val imageUriInput = inputData.getString(Constants.KEY_IMAGE_URI)
// Do the work
val response = upload(imageUriInput)
// Create the output of the work
val imageResponse = response.body()
val imgLink = imageResponse.data.link
// workDataOf (part of KTX) converts a list of pairs to a [Data] object.
val outputData = workDataOf(Constants.KEY_IMAGE_URI to imgLink)
return Result.success(outputData)
} catch (e: Exception) {
return Result.failure()
}
}
fun upload(imageUri: String): Response {
TODO(“Webservice request code here”)
// Webservice request code here; note this would need to be run
// synchronously for reasons explained below.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment