【发布时间】:2021-11-02 00:28:30
【问题描述】:
我正在使用 Kotlin 流和 LiveData 代码实验室做高级协程,并在 CacheOnSuccess.kt 中遇到了这个函数。
有一条注释说“// 注意:互斥锁不在此异步块中”。这到底是什么意思?为什么互斥锁不能保存在异步块中?那有什么意义呢?
suspend fun getOrAwait(): T {
return supervisorScope {
// This function is thread-safe _iff_ deferred is @Volatile and all reads and writes
// hold the mutex.
// only allow one coroutine to try running block at a time by using a coroutine-base
// Mutex
val currentDeferred = mutex.withLock {
deferred?.let { return@withLock it }
async {
// Note: mutex is not held in this async block
block()
}.also {
// Note: mutex is held here
deferred = it
}
}
// await the result, with our custom error handling
currentDeferred.safeAwait()
}
}
【问题讨论】:
标签: mutex android-livedata flow kotlin-coroutines