setupIsolateCommunication static method
- dynamic messageHandler(
- dynamic message
when sendToPort(message) is called in one isolate, messageHandler(message) will be invoked from the other isolate i.e. main_sendToPort -> background_messageHandler and vice-versa
Implementation
static Future<void> setupIsolateCommunication(
Function(dynamic message) messageHandler) async {
_receiveHandler = messageHandler;
if (_receivePort == null) {
_receivePort = new ReceivePort();
_receivePort.listen((data) {
final callHandler = _receiveHandler;
callHandler?.call(data);
() async {
if (callHandler == null) {
debugPrint(
"${DateTime.now()}: ${await isBackgroundIsolate ? "Background" : "Main"} isolate "
"received message $data, but receiveHandler is null.");
}
}();
});
final String portMappingName = (await isBackgroundIsolate)
? _BACKGROUND_ISOLATE_PORT_NAME
: _MAIN_ISOLATE_PORT_NAME;
IsolateNameServer.removePortNameMapping(portMappingName);
IsolateNameServer.registerPortWithName(
_receivePort.sendPort, portMappingName);
}
}