Segui i dati veloci senza rallentare
Una fotocamera, un microfono o un sensore possono cambiare data molte volte al secondo e subscribe gira a ogni cambiamento. Tieni un valore del genere fuori da subscribe e seguilo con onData(name, listener). Il suo listener riceve ogni nuovo valore di quel solo nome, lo scrive direttamente in un canvas o in un nodo di testo e lascia intatto il resto della vista. Il fonometro dell'esempio invia un nuovo livello venti volte al secondo.
import { useEffect, useRef } from 'react';
import { useWorld } from './useWorld.js';
// While you build, a fake sound meter sends a new level (0 to 1) every 50 ms.
const studio = {
name: 'Studio',
now: { text: 'Recording.' },
data: { level: { every: 50, value: (time) => Math.abs(Math.sin(time / 400)) * 0.7 + Math.random() * 0.3 } },
};
const STEP = 3; // pixels per level on the canvas
// onData draws the level on a canvas and in a label, without React state.
function LevelMeter({ world }) {
const canvas = useRef(null);
const label = useRef(null);
useEffect(() => {
const context = canvas.current.getContext('2d');
// onData calls this listener with each new level and for nothing else.
return world.onData('level', (level) => {
const { width, height } = canvas.current;
// Move the picture one step left, then draw the new level at the right.
context.drawImage(canvas.current, -STEP, 0);
context.clearRect(width - STEP, 0, STEP, height);
context.fillStyle = '#3d7ab8';
context.fillRect(width - STEP, height - level * height, STEP, level * height);
label.current.textContent = `${Math.round(level * 100)}%`;
});
// One call is enough, since `onData` works from any copy of `world`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<canvas ref={canvas} width="300" height="80" style={{ border: '1px solid #8888' }} />
{/* React never writes in this empty <span>, which leaves it free for onData. */}
<p>Level: <span ref={label} /></p>
</>
);
}
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: studio } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// This render also runs at every new level and only reads a name and a line of text.
return (
<>
<h2>{world.name}</h2>
<p>{world.now?.text}</p>
<LevelMeter world={world} />
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// While you build, a fake sound meter sends a new level (0 to 1) every 50 ms.
const studio = {
name: 'Studio',
now: { text: 'Recording.' },
data: { level: { every: 50, value: (time) => Math.abs(Math.sin(time / 400)) * 0.7 + Math.random() * 0.3 } },
};
const STEP = 3; // pixels per level on the canvas
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: studio } });
const title = document.createElement('h2');
const now = document.createElement('p');
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 80;
canvas.style.border = '1px solid #8888';
const levelLine = document.createElement('p');
const label = document.createElement('span');
levelLine.append('Level: ', label);
document.body.append(title, now, canvas, levelLine);
// subscribe, the slow part, also runs at every new level and only writes two texts.
world.subscribe((node) => {
title.textContent = node.name;
now.textContent = node.now?.text ?? '';
});
// onData, the fast part, calls this listener with each new level and for nothing else.
const context = canvas.getContext('2d');
world.onData('level', (level) => {
const { width, height } = canvas;
// Move the picture one step left, then draw the new level at the right.
context.drawImage(canvas, -STEP, 0);
context.clearRect(width - STEP, 0, STEP, height);
context.fillStyle = '#3d7ab8';
context.fillRect(width - STEP, height - level * height, STEP, level * height);
label.textContent = `${Math.round(level * 100)}%`;
});Come funziona
world.onData('level', listener) chiama listener con ogni nuovo livello e per nessun altro cambiamento. Restituisce una funzione che rimuove il listener e che l'effetto di React restituisce come cleanup per fermarlo quando il componente viene smontato. A ogni livello l'esempio sposta il canvas di un passo verso sinistra (drawImage copia il canvas su se stesso) e aggiunge una barra sul bordo destro. Questo ridisegno tocca pochi pixel invece dell'intera vista.
- In React il livello non entra mai nello stato. Il listener lo scrive sul canvas e in uno
<span>vuoto attraverso dei ref in cui React non scrive mai.useWorldfa comunque un re-render della vista a ogni cambiamento. Quel render si limita però a leggere un nome e una riga di testo e lascia invariato il DOM. - In JavaScript semplice
subscribescrive solo due testi. Quando il tuosubscribedisegna di più (per esempio una lista), fai come Parla con l'agente e ridisegna quella parte solo quando è cambiata.
Per quanto velocemente arrivino i dati, un cambiamento dei soli data fa girare subscribe al massimo una volta per frame di animazione. Nella webapp onData segue lo stesso ritmo. Disegna dall'ultimo valore che ricevi senza dare per scontato di riceverli tutti.
Vedi anche
- Segui le immagini della fotocamera: la stessa idea applicata a una fotocamera con un pulsante di pausa.
onData.- Prestazioni.