Solid · guide
Draw only what changed
Each time something arrives you get a new object, and every part of it that did not change is the same object as before. A screen can tell by comparing.
pnpm add @niscorp/solid zodStep 1 of 3
An answer with a card in it
A long text, and a card that is finished early.
import { z } from 'zod';
import { createStream } from '@niscorp/solid';
const Answer = z.object({
card: z.object({ show: z.string(), seats: z.array(z.string()) }),
text: z.string(),
});
const stream = createStream({ schema: Answer });Step 2 of 3
Listen to each part
A listener on a part is called once when it is added, and after that only when its part changed.
let card = 0;
let text = 0;
stream.select('card').on(() => (card += 1));
stream.select('text').on(() => (text += 1));Step 3 of 3
The card, then a long text
After the card has arrived, the text arrives in six pieces. The card is kept from before the text and compared after it.
stream.write('{"card":{"show":"The Tempest","seats":["C4","C5"]},"text":"');
const before = stream.current();
for (const word of ['Two ', 'seats ', 'together ', 'in ', 'row ', 'C."}']) stream.write(word);
const after = stream.current();
console.log('card listener:', card, '· text listener:', text);
console.log('same card:', before.card === after.card, '· same answer:', before === after);Then
Run it.
Each listener is called once when it is added. After that the card’s is called once, for the piece that brought the card, and the text’s once for each of its six pieces. The card is the same object before and after the text.
npx tsx changed.mtscard listener: 2 · text listener: 7 same card: true · same answer: false