客户端断开连接时如何从Firebase Realtime数据库中删除数据

时间:2019-02-05 13:09:18

标签: firebase firebase-realtime-database dart flutter

我正在开发一款游戏,可将两个玩家与Firebase实时数据库连接起来。但是我想要一种可以在玩家与互联网失去连接时删除其数据的方法。

1 个答案:

答案 0 :(得分:1)

这可以通过OnDisconnect方法进行更新。

This original answer from Frank最初描述了OnDisconnect方法的更多细节。

Read more about the interface here

您可以使用this Firebase example设置“已连接状态”,该功能使用带有OnDisconnect的实时数据库和云功能来显示用户状态。 从示例中拉出:

var userStatusDatabaseRef = firebase.database().ref('/status/' + uid);

firebase.database().ref('.info/connected').on('value', function(snapshot) {
    // If we're not currently connected, don't do anything.
    if (snapshot.val() == false) {
        return;
    };

    // If we are currently connected, then use the 'onDisconnect()'
    // method to add a set which will only trigger once this
    // client has disconnected by closing the app,
    // losing internet, or any other means.
    userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {
        // The promise returned from .onDisconnect().set() will
        // resolve as soon as the server acknowledges the onDisconnect()
        // request, NOT once we've actually disconnected:
        // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

        // We can now safely set ourselves as 'online' knowing that the
        // server will mark us as offline once we lose connection.
        userStatusDatabaseRef.set(isOnlineForDatabase);
    });
});