Skip to content

Service Setup

d-markey edited this page Jan 22, 2026 · 3 revisions

Service setup in Squadron allows you to initialize your services and configure the threads they run in. This can be done either on the worker side (background thread) or on the main thread side.


1. Worker-Side Setup

Initialize your services directly via their constructors. This is the most common way to provide configuration, dependencies, or initial state to a service.

How it Works

When you define a @SquadronService, squadron_builder automatically manages the transfer of constructor arguments from the main thread to the worker thread.

@SquadronService()
class MyService {
  // Arguments passed here will be managed by squadron_builder
  MyService(this.config, this.apiKey);

  final Map config;
  final String apiKey;

  @SquadronMethod()
  Future<void> doWork() async {
    // Service is already initialized with config and apiKey
  }
}

When instantiating the generated Worker or WorkerPool, you simply provide these arguments:

final worker = MyServiceWorker(config, apiKey);

2. Main-Thread Setup (PlatformThreadHook)

Sometimes you need to configure the thread itself (the Isolate or Web Worker) before it starts executing service commands. This is done on the main thread using a PlatformThreadHook.

How it Works

A PlatformThreadHook is a function that receives the underlying platform thread object (Isolate on Native, Worker on Web) and can perform low-level configurations.

Usage

You can provide a hook when starting a worker or pool. This is useful for:

  • Setting up custom Isolate properties (e.g., debug names, priorities).
  • Configuring Web Workers (e.g., adding event listeners at the platform level).

Definition

The PlatformThreadHook is defined as:

typedef PlatformThreadHook = FutureOr<void> Function(PlatformThread thread);
  • On Native: PlatformThread is an Isolate.
  • On Web: PlatformThread is a Worker from package:web.

Key Differences

Feature Worker-Side Setup Main-Thread Setup
Target The Service instance The Platform Thread (Isolate/Worker)
Location Background Thread Main Thread
Mechanism Constructor Arguments PlatformThreadHook
Best For Business logic initialization Low-level thread configuration

Clone this wiki locally