dartdart-isolates

Dart how to pass generic function to isolate


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) {
  // ...
}

Solution

  • Define a generic class

    class MyGenericClass<T> {
      T value;
    
      MyGenericClass(this.value);
    }
    

    Call the function in Isolate.

    Future<void> main() async {
      // Create an instance of MyGenericClass
      MyGenericClass<int> myInstance = MyGenericClass(5);
    
      // Spawn the isolate and pass the MyGenericClass instance
      final ReceivePort receivePort = ReceivePort();
      await Isolate.spawn(isolateFunction, receivePort.sendPort);
    
      // Send the MyGenericClass instance to the isolate
      final SendPort sendPort = await receivePort.first;
      sendPort.send(myInstance);
    
      // Receive the processed data from the isolate
      receivePort.listen((dynamic data) {
        if (data is MyGenericClass) {
          // Handle the processed data in the main isolate
          print('Processed value: ${data.value}');
    
          // Close the receive port to terminate the isolate
          receivePort.close();
        }
      });
    }
    

    Function to be executed in the isolate

    void isolateFunction(SendPort sendPort) {
      // Receive the MyGenericClass instance from the main isolate
      ReceivePort receivePort = ReceivePort();
      sendPort.send(receivePort.sendPort);
    
      receivePort.listen((dynamic data) {
        // Perform any processing on the generic class
        if (data is MyGenericClass) {
          // Process the data in the isolate
          data.value = data.value * 2;
    
          // Send the processed data back to the main isolate
          sendPort.send(data);
        }
      });
    }