Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear viewed WorkInfo in WorkManager, android?

Tags:

android

kotlin

When using WorkManager, I ran into the problem that the status of the operation is not deleted by the field of reading.

Here is the initialization operation

private fun saveCashCommandSchedule() {
    val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build()
    val work = OneTimeWorkRequestBuilder<WorkSynchronizeCashSchedule>()
            .setConstraints(constraints)
            .build()
    WorkManager.getInstance().enqueueUniqueWork("send_cash_schedule", 
    ExistingWorkPolicy.REPLACE, work)
}

Here I am connecting the listener to track the status of the operation

fun subscribeWorkScheduleCash(lifecycle: Lifecycle) {
    WorkManager.getInstance().getWorkInfosForUniqueWorkLiveData("send_cash_schedule").observe({
        lifecycle
    }, { states ->
        states?.forEach {
            if (it != null && it.state == WorkInfo.State.SUCCEEDED) {
                //TODO вот этой строки хотелось бы избежать
               // WorkManager.getInstance().pruneWork()
                loadData()
                return@observe
            }
        }
    })
}

Every time I connect a listener, the old status pops up. I need to somehow remove it. Using WorkManager.getInstance().pruneWork() is not an option, as it removes all the statuses of all operations that have completed their work.

Tell me, please, how to remove statuses.

like image 823
kvazik Avatar asked Jan 24 '26 20:01

kvazik


1 Answers

You need not to remove or prune the workinfo data received from workmanager as WorkManager takes care to auto-prune its work after a sane period of time.

This is mentioned in the JavaDoc for the pruneWork method:

/**
 * Cancels all unfinished work.  <b>Use this method with extreme caution!</b>  By invoking it,
 * you will potentially affect other modules or libraries in your codebase.  It is strongly
 * recommended that you use one of the other cancellation methods at your disposal.
 * <p>
 * Upon cancellation, {@link ListenableWorker#onStopped()} will be invoked for any affected
 * workers.
 *
 * @return An {@link Operation} that can be used to determine when the cancelAllWork has
 * completed
 */
public abstract @NonNull Operation cancelAllWork();

In the meantime , you can keep a database or store the tags in datastore (or sharedpref) for the work requests tags that you want to observe or get workinfo for , and observe only those and ignore rest.

like image 107
pradyumn Upadhyay Avatar answered Jan 27 '26 13:01

pradyumn Upadhyay



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!