For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/main-thread/main-thread-service.md.

LynxMainThread

A service that calls one of your main-thread scripts from Angular code, and gives you its return value. import { LynxMainThread } from '@blotch/angular-lynx';

Info

Template handlers such as (bindtap) already run on the main thread. Main-thread scripts explains when you need this API instead.

Usage

src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import {
  createMainThreadRef,
  LYNX_ELEMENTS,
  LynxMainThread,
  LynxMainThreadEvent,
  mainThreadFn,
} from '@blotch/angular-lynx';

const taps = createMainThreadRef(0);
const countTap = mainThreadFn(() => {
  taps.current++;
});
const readTaps = mainThreadFn(() => taps.current);

@Component({
  selector: 'app-root',
  imports: [LYNX_ELEMENTS, LynxMainThreadEvent],
  template: `
    <view [mainThreadBindtap]="countTap">
      <text>Tap me</text>
    </view>
    <view (bindtap)="showTaps()">
      <text>Taps so far: {{ shown() }}</text>
    </view>
  `,
})
export class App {
  readonly #mainThread = inject(LynxMainThread);
  readonly countTap = countTap;
  readonly shown = signal(0);

  async showTaps(): Promise<void> {
    this.shown.set(await this.#mainThread.runOnMainThread(readTaps));
  }
}

LynxMainThread is provided in root, so inject() it anywhere.

API

runOnMainThread(handle, ...args)

runOnMainThread<TArgs extends unknown[], TReturn>(
  handle: MainThreadFnHandle<TArgs, TReturn>,
  ...args: TArgs
): Promise<TReturn>;
  • handle: a function from mainThreadFn().
  • args: its arguments, checked against its parameter types.
  • Returns a promise of the function's return value. It rejects if the function throws or its promise rejects.

It runs the function right away. Your Angular code runs on the main thread, where the function is, so the call doesn't cross threads: arguments aren't copied, and a returned promise is awaited. Call it from anywhere in your app, such as an event handler, a constructor or an effect().