如何构建没有暂停功能的协程代码

时间:2019-02-21 21:08:36

标签: 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) }

    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成为暂停函数。我该怎么办?

1 个答案:

答案 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函数。