isolate_handler library

Effortless isolates abstraction layer.

What's an isolate?

In the words of the Dart documentation itself, isolates are:

Independent workers that are similar to threads but don't share memory, communicating only via messages.

In short, Dart is a single-threaded language, but it has support for concurrent execution of code through these so-called isolates.

This means that you can use isolates to execute code you want to run alongside your main thread, which is particularly useful for keeping your Flutter application running smoothly.

For more detailed information, please read this excellent article by Didier Boelens.

Using Isolate Handler

Spawning an isolate with Isolate Handler is really simple:

IsolateHandler().spawn(entryPoint);

This is similar to how isolates are spawned normally, with the exception that Isolate Handler does not expect a message parameter, only an entry point. Messaging has been abstracted away and a communications channel is instead opened automatically.

Communicating with an isolate

final isolates = IsolateHandler();
int counter = 0;

void main() {
  // Start a listener for ints sent from the isolate
  isolates.spawn<int>(entryPoint,
    name: "counter",
    // Executed every time data is received from the spawned isolate.
    onReceive: setCounter,
    // Executed once when spawned isolate is ready for communication.
    onInitialized: () => isolates.send(counter, to: "counter"),
  );
}

// Set new count and display current count
void setCounter(int count) {
  counter = count;
  print("Counter is now $counter");

  // We will no longer be needing the isolate, let's dispose of it
  isolates.kill("counter");
}

// This function happens in the isolate.
void entryPoint(Map<String, dynamic> context) {
  // Calling initialize from the entry point with the context is
  // required if communication is desired. It returns a messenger which
  // allows listening and sending information to the main isolate.
  final messenger = HandledIsolate.initialize(context);

  // Triggered every time data is received from the main isolate.
  messenger.listen((count) async {
   // Add one to the count and send the new value back to the main
   // isolate.
   messenger.send(++count);
  });
}

Classes

HandledIsolate<T>
Instance of FlutterIsolate handled by HandledIsolate.
HandledIsolateMessenger
Communication channel for sending data between HandledIsolate instances.
IsolateHandler
High-level isolate handler for Flutter.