【发布时间】:2018-10-12 19:56:15
【问题描述】:
运行一个 hello-world,将一些连续的真/假值写入 Firestore 数据库,目标是保持本地变量与云同步。
即使每个update() 调用在使用get() 启动下一个调用之前等待,回调事件似乎也出现了问题
我写“假”、“真”、“真” 但响应是“真”、“假”、“真”
即使是陌生人,有时也会有 3 个响应,即使我只提出了 2 个请求。下次我启动该应用程序时,是否有可能出现排队?如果是这样,有什么方法可以确保在关机前刷新?
我担心我的本地应用程序可能会对最近的值产生错误的印象。
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.firestore.FirestoreOptions
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val firestoreOptions = FirestoreOptions.newBuilder()
.setCredentials(GoogleCredentials.fromStream(
ClassLoader.getSystemClassLoader().getResourceAsStream("serviceAccountKey.json")))
.setTimestampsInSnapshotsEnabled(true)
.build()
val db = firestoreOptions.service!!
val docRef = db.collection("users").document("tmpUser").collection("devices").document("tmpDevice")
docRef.addSnapshotListener { snapshot, _ ->
(snapshot?.data ?: mapOf()).forEach { key, value ->
println(" RESPONSE: '$key'='$value'")
}
}
println("Listening...")
val writeResultFuture2 = docRef.update(mapOf("running" to false))
println("REQUEST 'false' at ${writeResultFuture2.get().updateTime}")
val writeResultFuture3 = docRef.update(mapOf("running" to true))
println("REQUEST 'true' at ${writeResultFuture3.get().updateTime}")
val writeResultFuture4 = docRef.update(mapOf("running" to true))
println("REQUEST 'true' at ${writeResultFuture4.get().updateTime}")
delay(5_000)
println("Stopping.")
}
输出:
Listening...
RESPONSE: 'running'='true'
RESPONSE: 'running'='false'
REQUEST 'false' at 2018-10-12T21:07:25.530943000Z
REQUEST 'true' at 2018-10-12T21:07:25.686950000Z
RESPONSE: 'running'='true'
REQUEST 'true' at 2018-10-12T21:07:25.686950000Z
Stopping.
【问题讨论】:
-
你能用这段代码打印出你最近一次运行的日志吗?
-
@ToddKerpelman 已编辑以包含输出。
标签: firebase kotlin google-cloud-firestore