我有一个名为saveAccount
fun saveAccount(id: Int, newName: String): Account {
val encryptedNames: List<String> = repository.findNamesById(id)
val decryptedNames: List<String> = encryptedNames.map { cryptographyService.decrypt(it) }
if(decryptedNames.contains(newName))
throw IllegalStateException()
return repository.save(newName)
}
我想同时解密所有名称,所以我做了:
suspend fun saveAccount(id: Int, newName: String): Account {
val encryptedNames: List<String> = repository.findNamesById(id)
val decryptedNames: List<String> = encryptedNames.map {
CoroutineScope(Dispatchers.IO).async {
cryptographyService.decrypt(it)
}
}.awaitAll()
if(decryptedNames.contains(newName))
throw IllegalStateException()
return repository.save(newName)
}
直到现在一切都很好,但问题是:我无法使saveAccount
成为暂停函数。我该怎么办?
答案 0 :(得分:0)
因此,您想在单独的协程中解密每个名称,但是saveAccount
仅在完成所有解密后才返回。
您可以使用runBlocking
:
fun saveAccount(id: Int, newName: String): Account {
// ...
val decryptedNames = runBlocking {
encryptedNames.map {
CoroutineScope(Dispatchers.IO).async {
cryptographyService.decrypt(it)
}
}.awaitAll()
}
// ...
}
这样saveAccount
不必是suspend
函数。