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}")
        }

 

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