Kotlin入门(三)使用协程

开启一个协程

fun main() {
    GlobalScope.launch { 
        println("开启了一个协程")
    }
}

创建多个协程

使用launch

runBlocking { 
        launch { 
            println("创建第一个协程")
        }
        launch { 
            println("创建第二个协程")
        }
    }

声明挂起函数

suspend

suspend fun printMessage() {
        println("声明一个挂起函数")
    }

coroutineScope

coroutineScope函数是一个挂起函数,它会继承外部协程的作用域并创建一个子作用域,它可以保证其作用域内的所有代码和子协程全部执行完之前,一直阻塞当前协程。

suspend fun printMessage()  = coroutineScope{
        println("声明一个挂起函数")
    }

取消协程

val job = GlobalScope.launch { 
        println("取消协程")
    }
    job.cancel()

比较常用的写法

 val job = Job()
    val scope = CoroutineScope(job)
    scope.launch { 
        println("统一管理协程")
    }
    job.cancel()

创建一个协程并获取它的执行结果

runBlocking { 
        val result = async { 
            5+5
        }.await()
        println(result)
    }

async并行写法

runBlocking {
        val deferred1 = async {

        }
        val deferred2 = async {

        }
        println("结果是:${deferred1.await() + deferred2.await()}")
    }

withContext

runBlocking {
        val result = withContext(Dispatchers.IO) {
            5+5
        }
        println(result)
    }

使用协程简化回调的写法

通常的网络请求写法

HttpUtil.sendHttpRequest(address, object: HttpCallbackListener {
	
	override fun onFinish(response: String) {
		//拿到数据
	}
	
	override fun onError(e: Exception) {
		//异常处理
	}
})

suspendCoroutine函数

"suspendCoroutine函数必须在协程作用域,或在挂起函数中才能调用,
它接收一个Lambda表达式,主要作用是将当前协程立即挂起,
然后在一个普通的线程中执行Lambda表达式中的代码。"

进行回调优化,首先定义一个request函数

suspend fun request(address: String): String {
        return suspendCoroutine { continuation ->
            HttpUtil.sendHttpRequest(address, object : HttpCallbackListener {
                override fun onFinish(response: String) {
                    continuation.resume(response)//恢复被挂起的协程,response成为suspendCoroutine函数的返回值
                }

                override fun onError(e: Exception) {
                    continuation.resumeWithException(e)
                }
            })
        }
    }

然后请求

suspend fun getBaiduResponse() {
        try {
            val response = request("https://www.baidu.com")
        } catch (e: Exception) {
            //异常处理
        }
    }

你可能感兴趣的:(Kotlin,kotlin,Android,Kotlin,for,Android)