如何解决子收集请求Firestore,协程
尝试坚持MVVM模式规则。最终数据应该到达ViewModel(我为Glide做了一个例外,但这不是重点)。
在文档中创建了几个子集合(喜欢,评论,图像等)。
创建它们后,我遇到了在主请求中请求Firestore的问题。数据只是没有时间到达。
在这种情况下,如何在“ data.add”之前等待数据?
ViewModel
init {
data = loadData()
}
fun getData(loadNextData: Boolean): LiveData<Response<List<Model>>> {
if (loadNextData)
data = loadData()
return data
}
private fun loadData(): LiveData<Response<List<Model>>> {
return liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
emit(Response.Loading)
val result = repository.loadData()
if (result is Response.Success || result is Response.Error)
emit(result)
}
}
存储库
suspend fun loadData(): Response<List<Model>> {
return suspendCoroutine { continuation ->
if (LAST_DOCUMENT == null) {
firebaseRepository.getReference(DEFAULT_COLLECTION_NAME,DEFAULT_ORDER_FIELD,DEFAULT_ORDER_DIRECTION)
} else {
firebaseRepository.getReference(DEFAULT_COLLECTION_NAME,DEFAULT_ORDER_DIRECTION,LAST_DOCUMENT!!)
}
.get()
.addOnSuccessListener { query ->
try {
LAST_DOCUMENT = query.documents.lastOrNull()
query.documents.forEach { document ->
document.toObject(ModelDTO::class.java)?.let {
it.id = document.id
it.likes_count = // TODO
it.comments_count = // TODO
it.images_uri.add(//TODO)
data.add(it.mapToEntity())
}
}
continuation.resume(Response.Success(data))
} catch (exception: Exception) {
continuation.resume(Response.Error(exception))
}
}
.addOnFailureListener { exception ->
continuation.resume(Response.Error(exception))
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。