world.subscribe(listener)
Calls your listener with the world immediately and again after every change. It returns a function that stops the calls.
const stop = world.subscribe((node) => draw(node));Parameters
| Parameter | What it is |
|---|---|
listener | The callback that receives the newest world (named node in the callbacks) immediately and then after every change. |
Returns
A stop() function that ends the calls of your listener and does no harm when called twice.
Usage
Draw the world at every change
Every view works this way. Your page never changes the world directly. It follows the world by rendering everything from node at each call.
const world = await connectToHost();
world.subscribe((node) => {
title.textContent = node.name;
status.textContent = node.now?.text ?? '';
sendButton.disabled = !node.canSend;
});Stop following
Keep the function returned by subscribe and call it when a part of your page goes away. In this example the view stops after three calls:
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world whose number of visitors changes every second.
const library = {
name: 'Library',
data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
// useWorld subscribes for you. Here we also call `subscribe` ourselves to see each call.
const { world, error } = useWorld({ fake: { world: library } });
const [lines, setLines] = useState([]);
const [isStopped, setIsStopped] = useState(false);
const isConnected = world !== null;
useEffect(() => {
if (!isConnected) return undefined;
// `subscribe` calls the function at once with the world, then after every change.
// It returns a function that stops it. This example stops after three calls.
let calls = 0;
const stop = world.subscribe((node) => {
calls += 1;
const line = `Call ${calls}: ${node.data.visitors} visitors`;
setLines((before) => [...before, line]);
if (calls === 3) {
stop();
setIsStopped(true);
}
});
return stop;
// Subscribe once, when the world arrives.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isConnected]);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<h2>{world.name}</h2>
<ol>
{lines.map((line) => <li key={line}>{line}</li>)}
</ol>
<p>{isStopped ? 'Stopped after 3 calls.' : ''}</p>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world whose number of visitors changes every second.
const library = {
name: 'Library',
data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: library } });
const title = document.createElement('h2');
const list = document.createElement('ol');
const note = document.createElement('p');
document.body.append(title, list, note);
// `subscribe` calls the function at once with the world, then after every change.
// It returns a function that stops it. This example stops after three calls.
let calls = 0;
const stop = world.subscribe((node) => {
calls += 1;
title.textContent = node.name;
const line = document.createElement('li');
line.textContent = `Call ${calls}: ${node.data.visitors} visitors`;
list.append(line);
if (calls === 3) {
stop();
note.textContent = 'Stopped after 3 calls.';
}
});The first call happens before subscribe returns. Each change brings a new call (here a new number of visitors every second).
In React
The useWorld hook calls subscribe for you and re-renders your component at every change. Call subscribe yourself only for work outside rendering. Do it in a useEffect that returns the stop function as the React tab above does.
Caveats
- The first call happens inside
subscribe. Create the elements that your listener fills before you subscribe. - Each call gets a new frozen world. Writing into it throws a
TypeError. Keep what you need in your own variables. - Many things count as a change: a new message, a new value in
data, a newnowor a change inwebappsuch as the theme or the keyboard. Render the whole world each time instead of guessing what changed. - Keep your listener quick. A world that shows a camera changes many times a second. When only
datachanges the kit calls your listener at most about once per screen frame. Even at that rate a slow listener slows your page. For one value that changes fast, useonData. - A listener that throws can prevent the other listeners from receiving that change. Catch errors inside your listener.
- You can subscribe more than once (for example once per part of your page) and each call has its own
stop.
Troubleshooting
subscribe never fails and has no error code.
| Problem | Why | What to do |
|---|---|---|
| The page shows the world as it was at the start. | The view rendered world once after connectToHost. That object is the first world and never changes. | Render from node inside subscribe. |
| A click handler sees old values. | The handler kept a world from an earlier call. | Read world.get() inside the handler. |
| The listener runs twice per change in React. | You subscribe in an effect that runs again at every render. | Subscribe once as in the React tab above or use the world returned by useWorld. |
See also
world.get(): the newest world outside the listener.world.onData(name, listener): one value ofdata.- Thinking in views: why a view renders the whole world every time.