backgroundFn and runOnBackground
Lets main-thread code call a function on the 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 explains when you need this API instead.
Usage
src/app/app.ts
runOnBackground is a global, so it needs no import. Its type comes with @blotch/angular-lynx.
API
backgroundFn(fn)
fn: the function to run on the background thread.- Returns a handle to pass to
runOnBackground().
runOnBackground(handle, ...args)
handle: a handle frombackgroundFn().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 anErrorthat 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
runOnBackgroundexists only on the main thread. A background function can't call another one with it.- Define
backgroundFnat 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. 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 fileuses __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 behindif (__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
MainThreadRefargument arrives as the background thread's copy of the ref, which only refs created at module scope have. - The function can be
async. It canawait fetch(), for example (see 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
Related
- Main-thread scripts guide
- Threads: where your code runs
LynxMainThread: the other direction
