gpt4 book ai didi

Firebase admin sdk java 实时数据库监听器

转载 作者:行者123 更新时间:2023-12-02 13:16:22 25 4
gpt4 key购买 nike

我正在尝试在 Kotlin 中实现 firebase admin SDK。我想在实时数据库中有一个监听器来监听来自这个数据库的更新。
我的问题是当我运行 main 函数时,运行开始然后立即完成该过程,而无需在实时数据库中监听更新。
这是我的代码:

fun main() {
val serviceAccount = FileInputStream("path/to/key.json")
val options = FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("URLDATABASE")
.build()

FirebaseApp.initializeApp(options)

val ref = FirebaseDatabase
.getInstance()
.getReference("/waitingList")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
print("TEST")
}

override fun onCancelled(databaseError: DatabaseError) {
println("The read failed: " + databaseError.code)
}
})
}

最佳答案

你的程序什么时候停止?您可以:
1 -> 在一个新的协程中启动它:

fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue

val serviceAccount = FileInputStream("path/to/key.json")
val options = FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("URLDATABASE")
.build()

FirebaseApp.initializeApp(options)

val ref = FirebaseDatabase
.getInstance()
.getReference("/waitingList")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
print("TEST")
}

override fun onCancelled(databaseError: DatabaseError) {
println("The read failed: " + databaseError.code)
}
})
}
}
2 ->在最后添加一段时间 sleep :
fun main() {

val serviceAccount = FileInputStream("path/to/key.json")
val options = FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("URLDATABASE")
.build()

FirebaseApp.initializeApp(options)

val ref = FirebaseDatabase
.getInstance()
.getReference("/waitingList")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
print("TEST")
}

override fun onCancelled(databaseError: DatabaseError) {
println("The read failed: " + databaseError.code)
}
})

while (true) {
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
}

关于Firebase admin sdk java 实时数据库监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63754498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com