Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Forked from kitsuniru/main.dart
Last active September 18, 2023 16:56
Show Gist options
  • Save PlugFox/06651db3cfd9e8bfc027f7637dc167d9 to your computer and use it in GitHub Desktop.
Save PlugFox/06651db3cfd9e8bfc027f7637dc167d9 to your computer and use it in GitHub Desktop.
'closure_1 as closure_2' problem
import 'dart:isolate';
void main() async {
final toMainIsolate = ReceivePort();
final stream = toMainIsolate;
void fn(ITargetAction action) => action.handleAction();
final worker = Worker<ITargetAction>(
port: toMainIsolate.sendPort,
action: TargetActionImpl(),
);
final isolate = await worker.spawn();
final sendPort = await stream.first as SendPort;
sendPort.send(fn);
}
abstract interface class ITargetAction {
void handleAction();
}
class TargetActionImpl implements ITargetAction {
@override
void handleAction() => print('HOORAY');
}
class Worker<T extends ITargetAction> {
Worker({
required SendPort port,
required T action,
}) : _port = port,
_action = action;
final SendPort _port;
final T _action;
static void _workerEndpoint<T extends ITargetAction>(Worker<T> worker) {
worker();
}
Future<Isolate> spawn() => Isolate.spawn<Worker<ITargetAction>>(
_workerEndpoint,
this,
);
void send(void Function(T) handler) => _port.send(handler);
void _receiveAction(void Function(T) handleAction) => handleAction(_action);
void call() => _port.send((ReceivePort()
..listen((data) {
if (data is! void Function(T)) return;
_receiveAction(data);
}))
.sendPort);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment