Advanced usage of 0x00 Workmanager
After the basic usage that has been learned in the previous article WorkManager
, let's look at some of its advanced uses today:
- Chained task calls
- Unique task Sequence
- Passing parameters and getting return values
0x01 Chained task (Chained tasks)
WorkManager
When performing multiple work tasks, you can specify the order of execution. Suppose there are 3 in an applicationOneTimeWorkRequest
Object:workA
、workB
、workC
。 These tasks need to be executed in sequence, so you can useWorkManager.beginWith()
Method JoinworkA
, this will return aWorkContinuation
Object that defines the execution sequence for the work task. And then call through it againWorkContinuation.then()
PutworkB
AndworkC
Join the execution queue and execute the lastWorkManager.enqueue()
Method.
Workmanager.getinstance () . Beginwith (Worka) //Note:WorkManager.beginWith () returns a // Workcontinuation object; The following calls is//to Workcontinuation methods and then (WORKB) //FYI, then () returns a new Workcontinuat Ion instance . Then (WORKC) . Enqueue ()
workmanager
executes in the specified order worka
, workb
, WORKC
. Returns worker if one of the work tasks is executed result.
, the entire execution sequence is stopped.
WorkManager.beginWith()
Method can pass multiple Worker
objects, representing a group of tasks that can be executed in parallel , and then calling the then()
method. The work tasks that follow will not be performed until the parallel task group has finished executing then
.
Workmanager.getinstance () ///First, parallel execution of the Worka1,worka2,worka3 three tasks . Beginwith (workA1, workA2, workA3) // When all three tasks are complete, start executing workb: . Then (WORKB) //finally parallel execution workc1,workc2. Then (workC1, workC2) . Enqueue ()
You can also WorkContinuation.combine()
create more complex linked task call sequences by means of methods. It can WorkContinuation
merge two objects, assuming that you want to invoke the following task sequence:
Val chain1 = workmanager.getinstance () . Beginwith (Worka) . Then (workb) Val chain2 = Workmanager.getinstance () . Beginwith (WORKC) . Then (workd) Val chain3 = Workcontinuation . Combine (chain1, chain2) . Then (Worke) Chain3.enqueue ()
This chain execution order is: sub-chain a->b and sub-chain c->d parallel execution, Worka
executes workb
, and WORKC
execute after execution workd
; then wait for workb
and workd
all finished and finally executed worke
.
It is important to note that WorkManager
there is no guarantee that the order of execution of two sub-chains may be chain1
chain2
faster or chain1
chain2
slower.
0x02 Unique Task sequence (unique work sequences)
In application development, you may add the same chained task multiple times, but you WorkManager
want only one chained task to execute, and you can use a unique task sequence to specify the processing rules for the chained task. Suppose, do a download file operation, to a file download link, we do not need to repeat the download, only need to add once, and then add this task, it is ignored, because we do not want to repeat the same file to download multiple times. So when adding two operations tasks with the same name as "Download", for a unique task sequence, you can ExistingWorkPolicy
specify the REPLACE
KEEP
added policy through, and APPEND
, in.
- Replace: The new task replaces the old
- KEEP: The new task will be discarded and the old task will be kept
- APPEND: Append, the old task executes and then executes the new task.
Use beginUniqueWork()
the method to create a task sequence, and you can specify a unique name. Then ExistingWorkPolicy
specify the replacement policy for the task
workcontinuation continuation = Mworkmanager . Beginuniquework ("Download", Existingworkpolicy.keep, Onetimeworkrequest.from (Cleanupworker))
0x03 passing parameters and getting return values
Task execution can pass parameters and get results to task execution. Use workrequst. Builder. Setinputdata ()
method passing a data
object, which is an object in Key-value form, using data. Builder
to create the. Prettyprinted >worker " class Prettyprint code-in-text prettyprinted "> worker. Getinputdata () gets the parameter.
Similarly, Worker
you can use the Worker.setOutputData()
set Data
return value of an object in. To get to this return value is passed LiveData<WorkStatus>
.
Give me a chestnut:
There is a download task in which you Worker
get the URL of the parameter passed in, then perform the download, and finally set the download result.
The result key:const val key_result = "Result" Class Downloadworker (Context:context, params:workerparameters): Work ER (context, params) { override Fun DoWork (): Result { //get parameter val url = getinputdata ("url") //Execute download C5/>val result = download (URL); Set download result val output:data = Mapof (Key_result to RESULT). Toworkdata () setoutputdata (Output) //Task execution succeeded return result.success }}
Then, by WorkRequest
passing the parameters
Constructs the download link parameter val urldata:data = mapof ("url" to "https://developer.android.com/images/topic/libraries/architecture/ Workmanager-chain.svg ") . Toworkdata ()//construct workrequest and pass the download parameters val downloadwork = onetimeworkrequest.builder< Downloadworker> () . Setinputdata (urldata). build ()//give Workmanager to perform task Workmanager.getinstance (). Enqueue (Downloadwork)
Finally, by WorkStatus
getting the return value
Workmanager.getinstance (). Getstatusbyid (Downloadwork.id) . Observe (this, Observer {status- if (status! = null && status.state.isFinished) { val myresult = status.outputData.getString (Key_result, Mydefaultvalue) //... do something with the result ... } )
0x04 Reference
https://developer.android.com/topic/libraries/architecture/workmanager/advanced
Https://developer.android.com/reference/androidx/work/ExistingWorkPolicy
Http://clmirror.storage.googleapis.com/codelabs/android-workmanager/index.html?index=..%2F..%2Findex#0
How to use Workmanager to perform background tasks (bottom)