runAsync<R, F> function

Future<R> runAsync<R, F>(
  1. F func,
  2. [List parameters]
)

Example

main() async {
  print(await runAsync<String, String Function(String)>(sing, ["lalalala"]));
  print(await runAsync<String, Function>(song));
}

String sing(String str) => "Singing: " + str;
String song() => "lololololo";

Implementation

Future<R> runAsync<R, F>(F func, [List<dynamic> parameters]) async {
  final receivePort = ReceivePort();
  await Isolate.spawn(asyncRunner, receivePort.sendPort);

  // The 'asyncRunner' isolate sends it's SendPort as the first message
  final sendPort = await receivePort.first;

  final responsePort = ReceivePort();
  sendPort.send([responsePort.sendPort, func, parameters ?? []]);
  final res = await responsePort.first;
  if (res is! R)
    return Future.error(res);
  else if (res == null) return null;
  return res as R;
}