Shi*_*lal 1 coroutine kotlin google-cloud-firestore kotlin-coroutines
下面的代码通过使用协程流从 firestore 获取数据,给出了我想要的结果。
suspend fun getFeedPer() = flow<State<Any>> {
emit(State.loading())
val snapshot = dbRef.collection("FeedInfo/FeedPercent/DOC/")
.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
.limit(1)
.get().await()
val post = snapshot.toObjects(FeedPer::class.java)
Log.d("TAG", "getFeedPer: ${snapshot.documents[0].id}")
Log.d("TAG", "getFeedPer: $post")
emit(State.success(post))
}.catch {
emit(State.failed(it.message.toString()))
}.flowOn(Dispatchers.IO)
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试向我的查询添加一个过滤器。为此,我正在使用任务。
val docRef=dbRef.collection("FeedInfo/FeedPercent/DOC/")
val task1=docRef.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
.limit(1).get()
val task2=docRef.whereLessThanOrEqualTo("bodyWeight", 0.80)
.limit(1).get()
Run Code Online (Sandbox Code Playgroud)
现在如何通过协程流程来完成它。
请帮忙谢谢
小智 5
您必须将任务放入 coroutineScope 中,其他一切都将与以前相同。
emit(State.loading())
var eMsg = ""
val docRef = dbRef.collection("FeedInfo/FeedPercent/DOC/")
val task1 = docRef.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
.limit(1).get()
val task2 = docRef.whereLessThanOrEqualTo("bodyWeight", 0.80)
.orderBy("bodyWeight", Query.Direction.DESCENDING)
.limit(1).get()
/** Need to do query Direction here to get correct data*/
coroutineScope {
val allTask: Task<List<QuerySnapshot>> = Tasks.whenAllSuccess(task1, task2)
allTask.addOnSuccessListener {
for (querySnapshot in it) {
for (documentSnapshot in querySnapshot) {
/** Do your code to get the data */
}
}
}.await()
allTask.addOnFailureListener {
eMsg = it.message.toString()
}
/** Emitting flow based on task status **/
if (allTask.isSuccessful) {
emit(State.success(WhatEverItIs))
} else {
emit(State.failed(eMsg))
}
}
}.catch {
emit(State.failed(it.message.toString()))
}.flowOn(Dispatchers.IO)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
323 次 |
| 最近记录: |