首页 > 解决方案 > 如何在应用表达式中调用挂起函数

问题描述

我想在 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) }

标签: androidkotlinkotlin-coroutinessuspend

解决方案


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来并行执行这些操作。


推荐阅读