SoulCache

Observer

Learn about SoulCache's observer system for reactive updates

Observer System

The Observer System manages subscriptions and reactive updates.

Usage

Subscribing to Queries

Use QueryClient.subscribe() to observe query updates:

import { QueryClient } from '@soulcache/core';
 
const client = new QueryClient();
 
// Subscribe to a query
const unsubscribe = client.subscribe(['users'], (snapshot) => {
  console.log(snapshot.data);
  console.log(snapshot.status);
});
 
// Cleanup when done
unsubscribe();

Multiple Queries

Subscribe to multiple query keys:

const unsub1 = client.subscribe(['users'], handleUsers);
const unsub2 = client.subscribe(['posts'], handlePosts);
 
// Cleanup all
unsub1();
unsub2();

Features

Automatic Deduplication

Multiple subscribers for the same key share updates:

const unsub1 = client.subscribe(['users'], handleUsers);
const unsub2 = client.subscribe(['users'], handlePosts);
// Both get notified with a single update

Synchronous Delivery

Updates are delivered synchronously. There is no notification batching in the current release: each state change results in an immediate notification to subscribers of that key. Subscribers for the same key are each notified as the underlying state transitions occur.

Equality Checking

Subscribers are only notified when data actually changes, preventing unnecessary re-renders.

Best Practices

Observer Guidelines

  • Always unsubscribe — Prevent memory leaks
  • Use stable keys — Don't create new arrays in render
  • Monitor observer count — Detect memory leaks early

On this page