用于实时数据库的Firebase管理员SDK Java监听器

时间:2020-09-05 13:36:23

标签: firebase kotlin firebase-realtime-database firebase-admin

我正在尝试在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 个答案:

答案 0 :(得分:2)

您的程序何时应该停止?您可以: 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->最后增加一会儿睡眠:

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
    }
}