繁体   English   中英

如何在应用表达式中调用暂停 function

[英]How to call a suspend function within a apply expression

我想在 apply { } 块中调用暂停 function 。
我有一个:

private suspend fun retrieve(accountAction: AccountAction): Any

suspend fun login() {  
 accountEvent.apply {  
  retrieve(it)
}

我试图用suspend { retrieve(it) } runblocking { retrieve(it) }包围它,但似乎即使它没有产生错误(只能在协程主体内调用暂停函数)代码也没有进入retrieve function,但只是通过它,这就是我的单元测试失败的原因。

仅供参考:这是 class,而不是活动或片段。

编辑:

这是实际代码(来自评论):

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) }

编辑:

这显示了一个不使用map的替代方案,因为在我的这个例子中它并不是真正需要的(除非你真的想链接你的所有电话)

suspend fun login(webView: WebView) { 
  val result = trackingId().flatMap { id -> AccountAction(client, id, WeakReference(webView), upgradeAccount) } 
  
  upgradeWebViewProgress(webView) 

  return retrieve(result).flatMap { updateAuth(it) } }

当您想对这样的元素列表执行异步(挂起)操作时,可以使用Flow -API。 您可以在此处阅读有关 API 的信息: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines.flow/kotlinx-coroutines.flow/kotlinx-coroutines-x/

让您的示例工作的最简单方法可能是将您的列表转换为Flow ,执行暂停操作,然后转换回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上使用其他运算符来并行执行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM