> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# `LynxMainThread`

A service that calls one of your [main-thread scripts](/guide/glossary.md#main-thread-script) 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](/guide/main-thread/index.md) explains when you need this API instead.
:::

## Usage

```typescript title="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)`

```typescript
runOnMainThread<TArgs extends unknown[], TReturn>(
  handle: MainThreadFnHandle<TArgs, TReturn>,
  ...args: TArgs
): Promise<TReturn>;
```

- **`handle`**: a function from [`mainThreadFn()`](/api/main-thread/main-thread-fn.md).
- **`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](/guide/glossary.md#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()`.

## Related

- [Main-thread scripts guide](/guide/main-thread/index.md)
- [`mainThreadFn`](/api/main-thread/main-thread-fn.md)
- [`backgroundFn`](/api/main-thread/background-fn.md): the other direction
