【问题标题】:How to struture coroutine code without suspend function如何在没有挂起功能的情况下构造协程代码
【发布时间】:2019-02-21 21:08:36
【问题描述】:

我有一个方法叫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 成为挂起函数。我该怎么办?

【问题讨论】:

    标签: kotlin kotlinx.coroutines


    【解决方案1】:

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

    您可以为此使用runBlocking

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

    这样saveAccount 不必是suspend 函数。

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 2020-02-27
      • 2015-03-15
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2016-06-03
      • 2012-11-03
      相关资源
      最近更新 更多