Kotlin/Android novice here :). I'm playing around with chunked uploads using a CoroutineWorker and don't see a built-in way to maintain state for my worker in case a retry happens, but I'm having sort of a hard time believing smth like that would be missing...
My use case is the following:
chunkIndex
is being tracked.Retry()
, the worker somehow retrieves the current chunk index and resumes rather than starting from at the beginning again.So basically, I really just need to preserve that chunkIndex
flag. I looked into setting progress, but this seems to be hit or miss on retries (worked once, wasn't available on another attempt).
override suspend fun doWork(): Result {
try {
// TODO check if we are resuming with a given chunk index
chunkIndex = ...
// do the work
performUpload(...)
return Result.success()
} catch (e: Exception) {
// TODO cache the chunk index
return Result.retry()
}
}
Did I overlook something, or would I really have to store that index outside the worker?
You have a pretty good use-case but unfortunately you cannot cache data within Worker
class or pass on the data to the next Worker
object on retry! As you suspected, you will have to store the index outside of the WorkManager
provided constructs!
Long answer,
The Worker
object can receive and return data. It can access the data from getInputData()
method. If you chain tasks, the output of one worker can be input for the next-in-line worker. This can be done by returning Result.success(output)
(see below code)
public Result doWork() {
int chunkIndex = upload();
//...set the output, and we're done!
Data output = new Data.Builder()
.putInt(KEY_RESULT, result)
.build();
return Result.success(output);
}
So the problem is we cannot return data for the retry case, only for failure and success case! (Result.retry(Data data)
method is missing!)
Reference: official documentation and API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With