Kotlin 如何构造没有挂起函数的协同程序代码

Kotlin 如何构造没有挂起函数的协同程序代码,kotlin,kotlinx.coroutines,Kotlin,Kotlinx.coroutines,我有一个方法叫saveAccount fun saveAccount(id: Int, newName: String): Account { val encryptedNames: List<String> = repository.findNamesById(id) val decryptedNames: List<String> = encryptedNames.map { cryptographyService.decrypt(it) }

我有一个方法叫
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)
}
fun saveAccount(id:Int,newName:String):Account{
val encryptedNames:List=repository.findNamesById(id)
val decryptedNames:List=encryptedNames.map{cryptographyService.decrypt(it)}
if(decryptedNames.contains(newName))
抛出非法状态异常()
返回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)
}
suspend fun saveAccount(id:Int,newName:String):Account{
val encryptedNames:List=repository.findNamesById(id)
val decryptedNames:List=encryptedNames.map{
CoroutineScope(Dispatchers.IO).async{
加密服务。解密(it)
} 
}.all()
if(decryptedNames.contains(newName))
抛出非法状态异常()
返回repository.save(newName)
}

到目前为止,一切都很好,但问题是:我不能使
saveAccount
成为挂起函数。我该怎么办?

因此,您希望在一个单独的协同程序中解密每个名称,但是
saveAccount
只应在所有解密完成后返回

您可以使用:

fun saveAccount(id: Int, newName: String): Account {
    // ...
    val decryptedNames = runBlocking {
        encryptedNames.map {
            CoroutineScope(Dispatchers.IO).async {
                cryptographyService.decrypt(it) 
            }
        }.awaitAll()
    }
    // ...
}

这样一来,
saveAccount
就不必是一个
suspend
函数。

因此,您希望在一个单独的协同程序中解密每个名称,但
saveAccount
只应在所有解密完成后返回

您可以使用:

fun saveAccount(id: Int, newName: String): Account {
    // ...
    val decryptedNames = runBlocking {
        encryptedNames.map {
            CoroutineScope(Dispatchers.IO).async {
                cryptographyService.decrypt(it) 
            }
        }.awaitAll()
    }
    // ...
}
这样
saveAccount
就不必是
suspend
功能