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

# `backgroundFn` and `runOnBackground`

Lets main-thread code call a function on the [background thread](/guide/glossary.md#background-thread), where background-only APIs live. `import { backgroundFn } 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 } from '@angular/core';
import {
  backgroundFn,
  LYNX_ELEMENTS,
  LynxMainThreadEvent,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

let lastColor = '';

// Registered on the background thread.
const rememberColor = backgroundFn((color: string) => {
  lastColor = color;
});

const paint = mainThreadFn((event: MainThread.TouchEvent) => {
  event.currentTarget.setStyleProperty('background-color', '#ff5722');
  void runOnBackground(rememberColor, '#ff5722');
});

@Component({
  selector: 'app-root',
  imports: [LYNX_ELEMENTS, LynxMainThreadEvent],
  template: `
    <view [mainThreadBindtap]="paint"><text>Tap to paint</text></view>
  `,
})
export class App {
  readonly paint = paint;
}
```

`runOnBackground` is a global, so it needs no import. Its type comes with `@blotch/angular-lynx`.

## API

### `backgroundFn(fn)`

```typescript
function backgroundFn<TArgs extends unknown[], TReturn>(
  fn: (...args: TArgs) => TReturn,
): BackgroundFnHandle<TArgs, TReturn>;
```

- **`fn`**: the function to run on the background thread.
- **Returns** a handle to pass to `runOnBackground()`.

### `runOnBackground(handle, ...args)`

```typescript
// A global on the main thread.
function runOnBackground(
  handle: { _wkltId: string },
  ...args: unknown[]
): Promise<unknown>;
```

- **`handle`**: a handle from `backgroundFn()`.
- **`args`**: its arguments. They aren't type-checked against the function.
- **Returns** a promise of the function's return value, typed `unknown`. If the function returns a promise, it waits for it. If the function throws or its promise rejects, it rejects with an `Error` that has the same message.

Call it from any of your Angular code, a main-thread function or a template event handler: they all run on the main thread.

## Constraints

- **`runOnBackground` exists only on the main thread.** A background function can't call another one with it.
- **Define `backgroundFn` at module scope.** The background thread loads each file that calls it there, with that file's imports, and none of your other code. So a function created in a class or another function never registers.
- **The file's other top-level code runs on both threads,** unless you [shrink the background thread's script](/guide/main-thread/index.md#shrink-the-background-threads-script). So does its imports'. Top-level code there can't call a main-thread-only element function such as `__CreateView()`: the build warns that the file `uses __CreateView at module level, which only exists on the main thread`, and on the device the file fails to load on the background thread. Call it from a function, or behind `if (__MAIN_THREAD__)`. A build with Rsbuild's persistent cache (`performance.buildCache`) doesn't warn, since it doesn't read cached modules again.
- **A file that loads lazily works,** such as a lazy route's. The background thread loads it at startup.
- **Arguments and the return value are copied as JSON.** A [`MainThreadRef`](/api/main-thread/main-thread-ref.md) argument arrives as the background thread's copy of the ref, which only refs created at module scope have.
- **The function can be `async`.** It can `await fetch()`, for example (see [Network requests](/guide/concepts/javascript-environment.md#network-requests)).
- **Signals it changes don't reach the screen.** Your app doesn't run on the background thread, so its signals there aren't the ones on screen. Return a value and set the signal on the main thread instead.

## Types

```typescript
// An opaque handle. Its fields are internal.
type BackgroundFnHandle<
  TArgs extends unknown[] = unknown[],
  TReturn = unknown,
> = {/* internal */};
```

## Related

- [Main-thread scripts guide](/guide/main-thread/index.md)
- [Threads: where your code runs](/guide/concepts/threads.md)
- [`LynxMainThread`](/api/main-thread/main-thread-service.md): the other direction
