android - 如何在应用表达式中调用挂起函数
问题描述
我想在 apply { } 块中调用挂起函数。
我有一个:
private suspend fun retrieve(accountAction: AccountAction): Any
suspend fun login() {
accountEvent.apply {
retrieve(it)
}
我试图用它包围它,suspend { retrieve(it) }
runblocking { retrieve(it) }
但似乎即使它没有产生错误(只能在协程主体内调用暂停函数),代码也没有进入检索函数,而是通过它,这就是我的单元测试失败的原因.
仅供参考:这是一个类,而不是一个活动或片段。
编辑:
这是实际代码(来自评论):
override suspend fun login(webView: WebView) = trackingId()
.flatMap { id -> AccountAction(client, id, WeakReference(webView), upgradeAccount) }
.map {
it.apply {
upgradeWebViewProgress(webView)
suspend { retrieve(it) }
}
}
.flatMap { updateAuth(it) }
解决方案
Flow
当您想对这样的元素列表执行异步(挂起)操作时,可以使用-API。您可以在此处阅读有关该 API 的信息:https ://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/
让您的示例工作的最简单方法可能是将您的列表转换为 a Flow
,执行挂起操作,然后转换回 a List
。像这样:
override suspend fun login(webView: WebView) = trackingId()
.flatMap { id -> AccountAction(client, id, WeakReference(webView), upgradeAccount) }
.asFlow()
.map {
it.apply {
upgradeWebViewProgress(webView)
retrieve(it)
}
}
.toList()
.flatMap { updateAuth(it) }
请注意,这可能不是最有效的,因为它将retrieve
按顺序执行 - 操作。例如,您可以使用其他运算符Flow
来并行执行这些操作。
推荐阅读
- java - 为什么在使用相同 AWS Lambda 函数的多个触发器将数据从 Mysql 迁移到 S3 时数据会重复
- azure - 需要帮助设置 Azure DevOps
- r - 使用 DT 包根据列值对两列进行条件格式
- python - 使用python中的用户输入值按列过滤数据
- javascript - 为什么 Promise.then() 只适用于箭头函数?
- php - 检查当月是否已有记录
- artifactory - jFrog 存储库上的 helm 图表 index.yaml 的 URL 错误(本地://.. 而不是 https://..)
- javascript - 在反应中观察变量的变化
- html - 悬停在一个链接上更改链接本身和另一个链接的颜色(反之亦然)
- python - 为什么我的卡尔曼滤波器的测量和估计是相同的?