Android WorkManager 协程并行 串行使用

启动一个周期任务

 private fun startWork() {
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        val periodicWorkRequest = PeriodicWorkRequestBuilder<OfflineWork>(15, TimeUnit.SECONDS)
            .setConstraints(constraints)
            .setBackoffCriteria(BackoffPolicy.LINEAR, PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
            .build()

        WorkManager.getInstance(this).enqueueUniquePeriodicWork("offlineWork", ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest)

    }

在Work中两个业务方法使用 suspend 修饰

  suspend fun one(msg: String): Int {
        Log.e("TAG", "$msg 1")
        delay(2000)
        return 1
    }

    suspend fun two(msg: String): Int {
        Log.e("TAG", "$msg 2")
        delay(4000)
        return 2
    }

doWork中执行 

        //并行
        GlobalScope.launch() {
            val sum = withContext(Dispatchers.IO) {
                val a1 = async { one("并行") }
                val a2 = async { two("并行") }
                val one = a1.await()
                val two = a2.await()
                one + two
            }
            Log.e("TAG", "work--两个方法返回值的和:${sum}")
        }

 

 //串行
        GlobalScope.launch() {
            val sum = withContext(Dispatchers.IO) {
                val a1 = async { one("串行") }
                val one = a1.await()
                val a2 = async { two("串行") }
                val two = a2.await()
                one + two
            }
            Log.e("TAG", "work--两个方法返回值的和:${sum}")
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章