Firebase 侦听器实际上是如何工作的? [英] How firebase listener actually work?

查看:38
本文介绍了Firebase 侦听器实际上是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 Android 上,当您向数据库添加侦听器时,底层的实际机制是如何工作的.它只是更频繁地拉动还是其他特殊的东西?

I'm wondering on Android, how the underlying actual mechanism work when you add an listener to the database. Is it just more frequent pulling or something else special?

更新:为了更清楚,我理解什么是侦听器,但我的意思是侦听"方案如何工作,客户端(Android)如何知道服务器上的数据已更改.只是定期拉吗?(Firebase 工程师已经做了很多努力来解决这个问题,让我们很容易).

Update: To make it clearer, I understand what a listener is, but I meant how does the 'listening' scheme work, how a client (Android) knows the data on the server changed. Is it just a periodical pulling? (and Firebase engineers already do the hard work to cover that and make it easy for us).

看起来 firebase 不是开源的.

Looks like firebase is not open-source.

// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        System.out.println(snapshot.getValue());
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});

推荐答案

免责声明:这是在撰写本文时对事物运作方式的简化描述.当您阅读它时,情况可能已经改变.

当您的应用连接到 Firebase 数据库时,它会打开一个从设备到 Firebase 服务器的网络套接字连接.此连接在您的应用程序的整个生命周期内保持打开状态,或者直到您调用 goOffline().

When your app connects to the Firebase Database, it opens a web socket connection from the device to a Firebase server. This connection stays open for the lifetime of your app or until you call goOffline().

当您附加侦听器时,客户端会将位置(和潜在的查询参数)发送到服务器.服务器将该侦听器添加到所有已连接客户端的所有侦听器的列表中.然后它还会发回该侦听器的初始数据.

When you attach a listener, the client sends the location (and potential query parameters) to the server. The server adds that listener to a list of all listeners of all connected clients. It then also sends back the initial data for that listeners.

每当向数据库提交写入操作时,服务器都会扫描侦听器.对于每个相关的侦听器,服务器通过打开的网络套接字向客户端发送更新.

Whenever a write operation is committed to the database, the server scans the listeners. For each relevant listener, the server sends an update to the client over the open web socket.

这篇关于Firebase 侦听器实际上是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆