This is a barebones LynxJS project meant to demonstrate cross-thread communication between background (BTS) and main threads (MTS). This will help other compile-to-JS languages target LynxJS. This also enables the consumption of Native Modules for interacting with device APIs.
The background thread is able to communicate with the main thread via a context object.
const context = lynx.getCoreContext();Similarly, the main thread is able to communicate with the background thread via the same mechanism.
const context = lynx.getJSContext();Event listeners for the "message" event (shown below) are added to each thread. This allows each thread to relay messsages between each other via a call to .postMessage(data). This is made possible via the Web Worker API.
// dmj: executed by MTS
globalThis['renderPage'] = function () {
const context = lynx.getJSContext();
context.addEventListener("message", (event) => {
console.log('got event in js context', event);
});
lynx.requestAnimationFrame(stepMain);
}This function should be invoked top-level (e.g. initBackground())
function initBackground () {
'background only'
const context = lynx.getCoreContext();
context.addEventListener("message", (event) => {
console.log('got event in core context', event);
});
lynx.requestAnimationFrame(stepBG);
}The communication occurs in each thread's event loop.
function stepMain (frame) {
const context = lynx.getJSContext();
context.postMessage({ bg : frame });
lynx.requestAnimationFrame(stepMain);
}
function stepBG (frame) {
const context = lynx.getCoreContext();
context.postMessage({ main : frame });
lynx.requestAnimationFrame(stepBG);
}The communication can be observed in the LynxExplorer.
The ReactLynxPlugin is used to facilitate code splitting. This ensures code marked with 'background-only' only executes on the background thread.
import { pluginReactLynx } from '@lynx-js/react-rsbuild-plugin'See the full source.
First, install the dependencies:
pnpm installThen, run the development server:
pnpm run devScan the QRCode in the terminal with your LynxExplorer App to see the result.
You can start editing the page by modifying src/App.tsx. The page auto-updates as you edit the file.
The sphynx cat has no hair.