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 });
});
EventBehavior
createdAppend (or prepend if prepend: true)
updatedReplace the item with matching key
deletedRemove 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'
});
EventBehavior
joinAdd or update by .key
leaveRemove by .key
setReplace all

cursor

Tracks cursor positions. Items keyed by .key.

export const cursors = live.stream(
  (ctx, docId) => 'cursors:' + docId,
  async () => [],
  { merge: 'cursor' }
);
EventBehavior
updateAdd or update by .key
removeRemove by .key
setReplace all

Which strategy should I use?

Your dataStrategy
A list of items (CRUD operations)crud
A single value that changesset
Activity feed / logslatest
Who’s onlinepresence
Mouse/cursor positionscursor

Was this page helpful?