MainThreadRef

A box that keeps a value between calls of your main-thread scripts, such as a tap count or the element a drag started on. import { createMainThreadRef, MainThreadRef } 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 } from '@angular/core';
import {
  createMainThreadRef,
  LYNX_ELEMENTS,
  LynxMainThreadEvent,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

const taps = createMainThreadRef(0);

const fade = mainThreadFn((event: MainThread.TouchEvent) => {
  taps.current++;
  event.currentTarget.setStyleProperty('opacity', String(1 / taps.current));
});

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

API

createMainThreadRef(initValue)

function createMainThreadRef<T>(initValue: T): MainThreadRef<T>;

Creates a ref holding initValue. It's the same as new MainThreadRef(initValue).

MainThreadRef<T>

class MainThreadRef<T> {
  constructor(initValue: T);
  current: T;
}
  • current: the value. Read it and assign to it from your main-thread functions.

Constraints

  • Each thread has its own copy. A value written on the main thread isn't seen by code on the background thread, and the reverse. Use a ref only from main-thread functions.
  • Use it from the function's closure. Don't pass it as an argument to runOnMainThread() or runOnBackground(): from the other thread, the function receives a plain object instead of the ref.
  • Create it at module scope, next to the functions that use it.
  • Changing it doesn't render anything. It isn't a signal.