Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

27.7. 协程

27.7.1. GlobalScope

27.7.1.1. DefaultDispatcher

				
GlobalScope.launch {
    while (true) {
        delay(1000)
        println("每秒执行一次")
    }
}
				
				

				
	GlobalScope.launch {
        //GlobalScope开启协程:DefaultDispatcher-worker-1
        Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name)
		//子线程中此处不可以做UI操作
		withContext(Dispatchers.Main){
            Toast.makeText(this@MainActivity, "协程中切换线程", Toast.LENGTH_SHORT).show()
        }
    }				
				
				

27.7.1.2. Dispatchers.Main

				
	GlobalScope.launch(Dispatchers.Main) {
        	//GlobalScope开启协程:main
            Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name)
            //可以做UI操作
            Toast.makeText(this@MainActivity, "GlobalScope开启协程", Toast.LENGTH_SHORT).show()
    }				
				
				

27.7.1.3. Dispatchers.IO

				
GlobalScope.launch(Dispatchers.IO) {
    if (AndroidManager.Device.scanMicrophone() && !State.usbMicrophone.get()) {
        aigcSpeech.speaking("蓝牙麦克风连接")
    }
    Log.d(TAG, "Bluetooth connected")
}				
				
				

27.7.2. lifecycleScope

27.7.2.1. 

lifecycleScope默认主线程,可以通过withContext来指定线程

				
lifecycleScope.launch {
    // do
    withContext(Dispatchers.IO) {
        // do
    }
}
 
// or
 
lifecycleScope.launch(Dispatchers.IO){
    // do
}
 
// or
 
lifecycleScope.launch {
    whenResumed {
        // do
    }
}
 
// or
 
lifecycleScope.launchWhenResumed {
    // do
}
				
				
				

27.7.2.2. 协程中串行任务

			
	private fun serialExecution() {
        lifecycleScope.launch {
            val startTime = System.currentTimeMillis()
            val a = getDataA()
            val b = getDataB()
            val sum = a + b
            //D/MainActivity: serialExecution: sum = 3,耗时:3008
            Log.d(TAG, "serialExecution: sum = $sum,耗时:${System.currentTimeMillis() - startTime}")
        }
    }

    private suspend fun getDataA(): Int {
        delay(1000)
        return 1
    }

    private suspend fun getDataB(): Int {
        delay(2000)
        return 2
    }
			
				

27.7.2.3. 携程并行执行任务

			
private fun parallelExecution(){
        lifecycleScope.launch {
            val startTime = System.currentTimeMillis()
            val a = lifecycleScope.async { getDataA() }
            val b = lifecycleScope.async { getDataB() }
            val sum = a.await() + b.await()
            //D/MainActivity: parallelExecution: sum = 3,耗时:2009
            Log.d(TAG, "parallelExecution: sum = $sum,耗时:${System.currentTimeMillis() - startTime}")
        }
    }
    
    private suspend fun getDataA(): Int {
        delay(1000)
        return 1
    }

    private suspend fun getDataB(): Int {
        delay(2000)
        return 2
    }			
			
				

27.7.2.4. 取消携程

			
private var job: Job? = null
    
job = lifecycleScope.launch {
    ...
}
job?.cancel()
    			
			
				

27.7.3. viewModelScope

27.7.3.1. await()

				
fun getMessageByViewModel() {
    viewModelScope.launch {
        val deferred = async(Dispatchers.IO) { getMessage("netkiller") }
        mMessage.value = deferred.await()
    }
}