Subscriptions are the core of Lark’s real-time capabilities. When data changes on the server, your callback fires with the updated data.For a conceptual overview of how subscriptions work under the hood (delta sync, shared views), see Subscriptions.
Basic usage
Call ref.on(eventType, callback) to start listening. It returns an unsubscribe function you call when you’re done:
import { LarkDatabase } from "@lark-sh/client";const db = new LarkDatabase("my-project/my-database", { anonymous: true });const unsubscribe = db.ref("scores/player1").on("value", (snapshot) => { console.log("Current score:", snapshot.val());});// Later, stop listeningunsubscribe();
The unsubscribe pattern works well with React’s useEffect cleanup, Vue’s onUnmounted, and similar framework lifecycle hooks.
Event types
value
Fires once with the initial data, then again every time anything at the location (or its children) changes. The callback receives the complete snapshot.
const unsubscribe = db.ref("game/state").on("value", (snapshot) => { const state = snapshot.val(); console.log("Full game state:", state);});
child_added
Fires once for each existing child, then again whenever a new child is added. The callback receives the child’s snapshot and the key of the previous child (for ordering).
Always unsubscribe when you no longer need updates. This frees up resources on both the client and server.
const unsubscribe = db.ref("data").on("value", callback);// Call it when doneunsubscribe();
Forgetting to unsubscribe is a common source of memory leaks and unexpected behavior. Always clean up your listeners when a component unmounts or a view is no longer active.