所以我有一个LiveData,我将它转换成一个异步函数,需要一段时间才能执行(比如有时需要2秒,有时需要4秒)。
有时调用耗时很长,有时非常快(取决于结果),有时是瞬间的(空结果)
问题是,如果我的LiveData中有两个连续的发射,有时第一个结果需要一段时间才能执行,第二个结果需要一瞬间,然后它将在第一个结果之前显示第二个结果,然后用较早的计算覆盖结果。
我想要的是顺序效果的mroe。(有点像RxJava concatMap)
private val _state = query.mapAsync(viewModelScope) { searchString ->
if (searchString.isEmpty()) {
NoSearch
} else {
val results = repo.search(searchString)
if (results.isNotEmpty()) {
Results(results.map { mapToMainResult(it, searchString) })
} else {
NoResults
}
}
}
@MainThread
fun <X, Y> LiveData<X>.mapAsync(
scope: CoroutineScope,
mapFunction: androidx.arch.core.util.Function<X, Y>
): LiveData<Y> {
val result = MediatorLiveData<Y>()
result.addSource(this) { x ->
scope.launch(Dispatchers.IO) { result.postValue(mapFunction.apply(x)) }
}
return result
}如何防止第二个结果覆盖第一个结果?
发布于 2021-02-17 22:57:21
@MainThread
fun <X, Y> LiveData<X>.mapAsync(
scope: CoroutineScope,
mapFunction: (X) -> Y,
): LiveData<Y> = switchMap { value ->
liveData(scope.coroutineContext) {
withContext(Dispatchers.IO) {
emit(mapFunction(value))
}
}
}https://stackoverflow.com/questions/66204416
复制相似问题