workmanager 合并多个任务链接 并传递参数

示意图


image.png

创建work

class WorkA(context: Context, params: WorkerParameters) : Worker(context,params){
    override fun doWork(): Result {
       try {
           Log.i("cccccccccccc","workA")
           return Result.success()
       }catch (e:Exception){
           return Result.failure()
       }
    }
}

class WorkB(context: Context, params: WorkerParameters) : Worker(context,params){
    override fun doWork(): Result {
       try {
           Log.i("cccccccccccc","WorkB")
           var data = Data.Builder()
                   .putString("key1","key1")
                   .putString("key2","key2").build();
           return Result.success(data)
       }catch (e:Exception){
           return Result.failure()
       }
    }
}

class WorkC(context: Context, params: WorkerParameters) : Worker(context,params){
    override fun doWork(): Result {
       try {
           Log.i("cccccccccccc","WorkC")
           return Result.success()
       }catch (e:Exception){
           return Result.failure()
       }
    }
}

class WorkD(context: Context, params: WorkerParameters) : Worker(context,params){
    override fun doWork(): Result {
       try {
           Log.i("cccccccccccc","WorkD")
           var data = Data.Builder()
                   .putString("key1","key3")
                   .putString("key2","key4").build();
           return Result.success(data)
       }catch (e:Exception){
           return Result.failure()
       }
    }
}

class WorkE(context: Context, params: WorkerParameters) : Worker(context,params){
    override fun doWork(): Result {
       try {
           Log.i("cccccccccccc","WorkE")
          var key1 =  inputData.getStringArray("key1")
           var key2 = inputData.getStringArray("key2");
           Log.i("ccccccccccc","==key1=="+key1?.joinToString(","))
           Log.i("ccccccccccc","==key2=="+key2?.joinToString(","))
           return Result.success()
       }catch (e:Exception){
           return Result.failure()
       }
    }
}

执行

   var chain1 =  WorkManager.getInstance().beginWith(OneTimeWorkRequest.from(WorkA::class.java))
                .then(OneTimeWorkRequest.from(WorkB::class.java))

        var chain2 = WorkManager.getInstance().beginWith(OneTimeWorkRequest.from(WorkC::class.java))
                .then(OneTimeWorkRequest.from(WorkD::class.java))
        WorkContinuation.combine(mutableListOf(
                chain1,chain2
        )).then(OneTimeWorkRequest.Builder(WorkE::class.java)
                .setInputMerger(ArrayCreatingInputMerger::class.java)
                .build())
                .enqueue()

输出

workA
WorkC
WorkB
WorkD
WorkE
==key1==key1,key3
==key2==key2,key4

你可能感兴趣的:(workmanager 合并多个任务链接 并传递参数)