【发布时间】:2021-04-02 00:12:46
【问题描述】:
我想在 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) }
【问题讨论】:
-
我试过你的代码,填写了你没有提供的部分,对我来说效果很好。在
apply中挂起可以正常工作,因为它是一个内联函数。您能否提供一个最小但完整的示例来重现该问题? -
我删除了我的答案,因为它对您的情况没有帮助(正如@marstran 指出的那样)。请提供更详细的示例,以便我们尝试找到更好的解决方案。
-
这是主要代码。
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) } -
当我在单元测试中模拟检索乐趣的返回时。我得到一个值,就好像检索乐趣从未触发过一样。
-
重新排序你的函数怎么样:
fun login(webView: WebView) { val result = trackingId().flatMap { id -> AccountAction(client, id, WeakReference(webView), upgradeAccount) } upgradeWebViewProgress(webView) val retrieved = retrieve(result) return retrieved.{ updateAuth(it) } }
标签: android kotlin kotlin-coroutines suspend