【问题标题】:How do I delete data from Firebase Realtime Database when a client loses connection客户端断开连接时如何从 Firebase 实时数据库中删除数据
【发布时间】:2019-02-05 13:09:17
【问题描述】:

我正在开发一款将两个玩家与 firebase 实时数据库连接的游戏。但我想要一种方法来在失去与 Internet 的连接时删除玩家数据。

【问题讨论】:

  • 使用 OnDisconnect 功能对您有用吗? firebase.google.com/docs/reference/js/… 您可以使用触发器更新“在线”集合,该触发器会监视“断开连接”值。
  • 这仅适用于 Cloud Functions,因为您无法在没有连接的情况下更改任何内容..
  • @OneLunchMan 这听起来确实像解决方案。你能把它写在答案中吗?可能使用文档中的一些代码 sn-ps,并链接到一些以前的答案,例如 stackoverflow.com/a/42825006stackoverflow.com/a/30670928

标签: firebase firebase-realtime-database dart flutter


【解决方案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);
    });
});

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 2016-09-20
    • 2021-06-04
    • 1970-01-01
    • 2021-09-20
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多