WorkManager系列(八)Unique work

Unique work is a powerful concept that guarantees that you only have one chain of work with a particular name at a time. Unlike ids, unique names are human-readable and specified by the developer instead being auto-generated by WorkManager. Unlike tags, unique names are only associated with one chain of work.

You can create a unique work sequence by calling WorkManager.enqueueUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest) or WorkManager.enqueueUniquePeriodicWork(String, ExistingPeriodicWorkPolicy, PeriodicWorkRequest). The first argument is the unique name - this is the key we use to identify the WorkRequests. The second argument is the conflict resolution policy, which specifies what WorkManager should do if there's already an unfinished chain of work with that unique name:

  • Cancel the existing chain and REPLACE it with the new one.
  • KEEP the existing sequence and ignore your new request.
  • APPEND your new sequence to the existing one, running the new sequence's first task after the existing sequence's last task finishes. You cannot use APPEND with PeriodicWorkRequests.

Unique work can be useful if you have a task that shouldn't be enqueued multiple times. For example, if your app needs to sync its data to the network, you might enqueue a sequence named "sync", and specify that your new task should be ignored if there's already a sequence with that name. Unique work sequences can also be useful if you need to gradually build up a long chain of tasks. For example, a photo editing app might let users undo a long chain of actions. Each of those undo operations might take a while, but they have to be performed in the correct order. In this case, the app could create an "undo" chain and append each undo operation to the chain as needed.

 

Finally, if you need to create a chain of unique work, you can use WorkManager.beginUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest) instead of beginWith().

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值