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 throws, it rejects with anErrorwhose message is the thrown value as a string.
You can call it from a main-thread function or from a template event handler, since both run on the main thread.
Constraints
runOnBackgroundexists only on the main thread. Code in a constructor orngOnInitalso runs on the background thread, where calling it throws.- Define
backgroundFnat module scope. The call finds the function by an ID, which matches on both threads only for module-level functions. - Arguments and the return value are copied as JSON.
- The function must return synchronously. A returned promise isn't awaited: the caller receives
{}, so anasyncfunction's result is lost. - Signals it changes don't reach the screen. It runs in the background copy of your app, which isn't shown. 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
