Merge Strategies
The merge option on live.stream() controls how published events are applied to the store.
live.stream('todos', fn, { merge: 'crud' }) crud (default)
Maintains an array keyed by id. Handles created, updated, deleted events.
export const todos = live.stream('todos', async (ctx) => {
return db.todos.all();
}, { merge: 'crud', key: 'id' });
export const addTodo = live(async (ctx, text) => {
const todo = await db.todos.insert({ text });
ctx.publish('todos', 'created', todo);
});
export const removeTodo = live(async (ctx, id) => {
await db.todos.delete(id);
ctx.publish('todos', 'deleted', { id });
}); | Event | Behavior |
|---|---|
created | Append (or prepend if prepend: true) |
updated | Replace the item with matching key |
deleted | Remove the item with matching key |
set
Replaces the entire value. Good for counters, status indicators, aggregated data.
export const stats = live.stream('stats', async (ctx) => {
return { users: 42, messages: 1337 };
}, { merge: 'set' }); Any event name replaces the store value with the event data.
latest
Ring buffer of the last N events. Good for activity feeds and logs.
export const activity = live.stream('activity', async (ctx) => {
return db.activity.recent(100);
}, { merge: 'latest', max: 100 }); presence
Tracks connected users with join and leave events. Items keyed by .key.
export const online = live.stream('presence:lobby', async () => [], {
merge: 'presence'
}); | Event | Behavior |
|---|---|
join | Add or update by .key |
leave | Remove by .key |
set | Replace all |
cursor
Tracks cursor positions. Items keyed by .key.
export const cursors = live.stream(
(ctx, docId) => 'cursors:' + docId,
async () => [],
{ merge: 'cursor' }
); | Event | Behavior |
|---|---|
update | Add or update by .key |
remove | Remove by .key |
set | Replace all |
Which strategy should I use?
| Your data | Strategy |
|---|---|
| A list of items (CRUD operations) | crud |
| A single value that changes | set |
| Activity feed / logs | latest |
| Who’s online | presence |
| Mouse/cursor positions | cursor |
Was this page helpful?