@Synchronized在KMM中未按预期工作



我有一个Ktor类,我需要对未经授权的异常执行操作(当令牌过期时(,对于此操作,我需要有synchronized操作,否则它无法正常工作,问题是@Synchronized没有同步该操作,也没有等待下一个操作完成。

fun ktorFunction(){
HttpResponseValidator {
handleResponseException { exception ->
kermit.e { "In ${exception.message}" }
val clientException =
exception as? ClientRequestException ?: return@handleResponseException
val exceptionResponse = clientException.response
when (exceptionResponse.status) {
HttpStatusCode.Unauthorized -> {
test(){
kermit.v { "Error message" }
}
}
}
}
}


@Synchronized
fun test(messageTest: () -> Unit) {
CoroutineScope(Dispatchers.Default).launch {
delay(3000)
messageTest()
}
}

这个想法是,我希望test函数在完成之前不从其他线程调用,无论其中有什么操作

launch是一个异步启动协程并立即返回的函数,因此它的行为是正常的。如果你想同步协同程序,你应该使用Mutex。

在前面的例子中,我将不讨论它,但是IMO,如果你不打算管理它的生命周期,那么创建CoroutineScope就是一种代码气味。

private val testMutex = Mutex()
fun test(messageTest: () -> Unit) {
CoroutineScope(Dispatchers.Default).launch {
testMutex.withLock {
delay(3000)
messageTest()
}
}
}

最新更新