3

Is there a way to pass a generic Function as Parameter to an Isolate at spawn? I have attached a simplifyed version of my code (not working) but is there a way to archive this without dynamics? Or is the Type of the functionToCall decided at runtime and not at complietime and so not possible to decide for an isolate?

import 'dart:isolate';

class TestClass {
  // ...
}

void main(List<String> args) {
  ReceivePort receivePort = ReceivePort();

  Isolate.spawn(functionToCall<TestClass>, receivePort.sendPort);
}

void functionToCall<T>(SendPort sendPort) {
  // ...
}
timoxd7
  • 125
  • 6

2 Answers2

0

Everything about a generic type is known as part of the compilation, and "reified" for the same information to be double-checked at Runtime.

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
  • 1
    Okay thats good :) but how can i than pass a generic function to the Isolate.spawn method? I come from C++ where it is no problem with templates and using it as i have shown in my example. – timoxd7 Dec 22 '20 at 21:16
  • You probably need just one API per Isolate. If you have more APIs, spawn more Isolates. :) – Randal Schwartz Dec 22 '20 at 21:35
0

I think the problem here maybe not so much with Isolates, but that I don't know of any way in Dart that you can have create a function reference to a generic function.

eg, you can call certainly call your generic function:

functionToCall<TestClass>(myPort);

But I dont see how you can create a reference to the function for a specific type (TestClass) and its a function reference that you need too pass into the spawn method, so I think thats the limitation in Dart that you are running into here.

Maks
  • 7,562
  • 6
  • 43
  • 65