kotlin 中获取异步操作的返回值
async
async 会开启协程,然后调用 async 返回的 Deferred 的 await() 方法,即可获取 async 协程运算的结果。具体的代码示例如下:
CoroutineScope(Dispatchers.Default).launch {
val job = async {
println("async 正在执行")
return@async "返回值"
}
delay(1000)
println("async 返回结果:${job.await()}")
}
运行结果:
async 正在执行
async 返回结果:返回值
suspendCoroutine 、suspendCancellableCoroutine 我们将异步操作转化为同步代码风格
与 async 不同,suspendCoroutine 、suspendCancellableCoroutine 只是一个挂起函数,无法开启协程,所以,需要在其它协程作用域里面使用,然后将当前协程挂起。
suspendCoroutine 可以通过以下三个方法返回执行结果
resume
resumeWithException
resumeWith
suspendCancellableCoroutine 相当于是对 suspendCoroutine 的一次封装,可以 cancel 任务,在 invokeOnCancellation 方法中用来监听协程取消, 当协程被取消的时候会被回调。还增加了一些状态,suspendCancellableCoroutine 有以下几种状态:
isActive 是否活跃
isCancelled 是否取消
isCompleted 是否执行完成
suspendCoroutine、suspendCancellableCoroutine异常情况补充
- 当使用 suspendCoroutine 或者 suspendCancellableCoroutine 的时候,在调用 resume() 之后,后续的代码会被执行吗?若多次调用 resume() 又会怎么样?
实验:
CoroutineScope(Dispatchers.Default).launch {
try{
val result = suspendCancellableCoroutine<String>{
println("suspendCancellableCoroutine 正在执行")
it.resume("返回值")
println("suspendCancellableCoroutine 已经返回")
it.resume("返回值2")
println("suspendCancellableCoroutine 再次返回")
}
println("suspendCancellableCoroutine 执行成功,返回结果:$result")
}catch (e: java.lang.Exception){
println("suspendCancellableCoroutine 执行失败,返回异常:$e")
}
}
运行结果:
suspendCancellableCoroutine 正在执行
suspendCancellableCoroutine 已经返回
suspendCancellableCoroutine 执行失败,返回异常:java.lang.IllegalStateException: Already resumed, but proposed with update 返回值2
- 在使用 suspendCancellableCoroutine 后,若已经 cancel() 后,再调用 resume() ,会怎样?是会直接抛出异常的,我们需要注意异常的捕获。
示例如下:
CoroutineScope(Dispatchers.Default).launch {
try{
val result = suspendCancellableCoroutine<String>{
println("suspendCancellableCoroutine 正在执行")
cancel()
it.resume("返回值")
}
println("suspendCancellableCoroutine 执行成功,返回结果:$result")
}catch (e: java.lang.Exception){
println("suspendCancellableCoroutine 执行失败,返回异常:$e")
}
}
运行结果:
suspendCancellableCoroutine 正在执行
suspendCancellableCoroutine 执行失败,返回异常:kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; job=StandaloneCoroutine{Cancelling}@e9b1ab
- 调用 resume() 之后,后续代码还会继续执行。
- 第二次调用 resume() 后,后续代码不会被执行,并且会抛出异常,这一点,suspendCoroutine 和 suspendCancellableCoroutine 都是一样的。
- 在使用 suspendCancellableCoroutine 后,若已经 cancel() 后,再调用 resume() ,是会直接抛出异常的,需要注意异常的捕获。
- 当一个挂起函数中的suspendCancellableCoroutine函数被恢复(例如,通过调用continuation.resume或continuation.resumeWithException)后,该协程就不再挂起,并且不能再被取消。因此,在恢复之后,该协程将无法响应invokeOnCancellation函数。