Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android worker - update and preserve state across retries

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:

  1. Create the worker request with the path to the file to upload as input data
  2. Worker loops over the file and performs uploads in chunks. The latest uploaded chunkIndex is being tracked.
  3. In case of an error and subsequent 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?

like image 649
Philipp Sumi Avatar asked Oct 18 '25 17:10

Philipp Sumi


1 Answers

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.

like image 142
Binary Baba Avatar answered Oct 20 '25 07:10

Binary Baba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!