0Pricing
Firebase Auth & Realtime Database Apps · 课时

监听实时变更

通过订阅 Realtime Database 事件,让应用真正实现实时更新;实时响应值和子节点的变更,并清理监听器以避免资源泄漏。

监听实时变更 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Firebase Auth & Realtime Database Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

From Fetch to Stream

Reading data once gives you a snapshot. The power of Realtime Database is live updates: your app reacts the instant data changes on the server, with no polling.

This is done by attaching listeners to a location in the database.

The Value Event

The most common listener is value. It fires once immediately with current data, then again every time anything under that location changes.

import { getDatabase, ref, onValue } from 'firebase/database';

const db = getDatabase();
onValue(ref(db, 'scores/global'), (snapshot) => {
  console.log('New value:', snapshot.val());
});

Reading the Snapshot

The callback receives a DataSnapshot. Use .val() for the data, .exists() to check presence, and .key for the node name.

onValue(ref(db, 'user/42'), (snap) => {
  if (snap.exists()) {
    console.log(snap.key, snap.val());
  }
});

Child Events

For lists, value events resend the whole node on every change. Child events are more efficient, firing per item:

  • onChildAdded
  • onChildChanged
  • onChildRemoved

Using onChildAdded

onChildAdded fires once for each existing child, then for every new one. It is perfect for chat messages or feeds.

import { onChildAdded } from 'firebase/database';

onChildAdded(ref(db, 'messages'), (snap) => {
  appendMessage(snap.key, snap.val());
});

Reacting to Changes and Removals

Pair additions with change and removal handlers to keep your UI in sync without re-rendering everything.

import { onChildChanged, onChildRemoved } from 'firebase/database';

onChildChanged(ref(db, 'messages'), s => updateMessage(s.key, s.val()));
onChildRemoved(ref(db, 'messages'), s => removeMessage(s.key));

Reading Once

Sometimes you want current data without an ongoing subscription. Use get for a one-time read instead of a listener.

import { get } from 'firebase/database';

const snap = await get(ref(db, 'config'));
console.log(snap.val());

Detaching Listeners

Listeners stay active until removed, consuming bandwidth and memory. Always detach them when a screen unmounts, using the unsubscribe function returned by onValue.

const unsubscribe = onValue(ref(db, 'scores'), cb);
// later, when leaving the screen:
unsubscribe();

Handling Errors

Listeners can fail, often due to Security Rules denying read access. Provide an error callback so failures are visible, not silent.

onValue(ref(db, 'private'), (snap) => render(snap), (error) => {
  console.error('Read failed:', error.message);
});

Performance Tips

Keep listeners efficient:

  • Listen at the smallest path that has the data you need
  • Prefer child events for large lists
  • Never attach a value listener to the database root

A Live Counter Example

Putting it together: attach a value listener to a counter node, update the DOM in the callback, and unsubscribe on cleanup. The number changes for every connected client in real time.

const unsub = onValue(ref(db, 'visitors/count'), (snap) => {
  document.getElementById('count').textContent = snap.val() ?? 0;
});

Quick Check

Test your understanding of realtime listeners.

Recap

Your app can now respond to data the moment it changes.

  • Use onValue for single nodes
  • Use child events for efficient lists
  • Read once with get when no subscription is needed
  • Always detach listeners and handle errors
  • Listen at the narrowest useful path

常见问题解答

「监听实时变更」课时是免费的吗?

是的 — 「监听实时变更」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

「监听实时变更」这节课中我会学到什么?

通过订阅 Realtime Database 事件,让应用真正实现实时更新;实时响应值和子节点的变更,并清理监听器以避免资源泄漏。 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Firebase Auth & Realtime Database Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「监听实时变更」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?

能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 实时数据库基础
  2. 读取与写入数据
  3. 构建数据结构
  4. 监听实时变更
← 返回 Firebase Auth & Realtime Database Apps