【发布时间】:2021-05-13 04:01:59
【问题描述】:
在我当前的项目中,我正在逐渐从 RXJava 过渡到 Coroutines。我有一种情况,我需要停止执行并等待回调返回的结果。我已通过以下方式将我的 RXJava 方法转换为使用协程:
suspend fun fetchProducts(ids: List<String>) = suspendCoroutine<List<ProductItem>> { continuation ->
val getProducts = repo.search(ids, null, null)
getProducts.subscribe(
{ callResult ->
productRequestInProgress.postValue(false)
continuation.resume(callResult.result())
},
{ error ->
productRequestInProgress.postValue(false)
//continuation.resumeWithException(t)
}
)
}
我正在从 .mapByPage 函数调用 fetchProducts 方法,但我收到消息 “暂停函数 'await' 只能从协程或其他暂停函数中调用” em> 。关于如何正确调用 fetchProducts 函数并等待 mapByPage 函数中的结果的任何想法?这是我收到错误消息的地方。谢谢
val dataSourceFactory = SearcherSingleIndexDataSource.Factory(searcher) { hit ->
Product(hit.json.getValue("id").jsonPrimitive.content)
}.mapByPage { it ->
viewModelScope.launch {
fetchProducts(it.mapNotNull { it.id })
}.await()
}
【问题讨论】:
标签: android kotlin kotlin-coroutines algolia