handleData method
void
handleData(
- dynamic msg
Implementation
void handleData(dynamic msg) {
if (onReceivedMessageHandler != null) {
onReceivedMessageHandler!(msg);
}
if (msg == null || msg is! Map) {
return;
}
String? type = msg['t'];
type ??= msg['type'];
if (type == null) {
return;
}
if (type == 'send_port') {
_sendPort = msg['port'];
if (!_readyCompleter.isCompleted) {
_readyCompleter.complete();
}
} else if (type == 'data') {
_controller.add(msg['d']);
} else if (type == 'error') {
_controller.addError(msg['e']);
} else if (type == 'ping') {
_sendPort.send(<String, dynamic>{'t': 'pong', 'i': msg['i']});
} else if (type == 'pong') {
String id = msg['i'];
if (_pings.containsKey(id)) {
_pings[id]?.complete();
_pings.remove(id);
}
} else if (type == 'req') {
_handleRequest(msg['n'], msg['i'], msg['a']);
} else if (type == 'res') {
int id = msg['i'];
dynamic result = msg['r'];
dynamic err = msg['e'];
if (err != null) {
if (_responseHandlers.containsKey(id)) {
_responseHandlers
.remove(id)
?.completeError(err, StackTrace.fromString(msg['s']));
} else {
throw Exception('Invalid Request ID: $id');
}
} else {
if (_responseHandlers.containsKey(id)) {
_responseHandlers.remove(id)?.complete(result);
} else {
throw Exception('Invalid Request ID: $id');
}
}
} else if (type == 'stop') {
if (!_stopCompleter.isCompleted) {
_stopCompleter.complete();
}
_sendPort.send({'t': 'stopped'});
} else if (type == 'stopped') {
if (!_stopCompleter.isCompleted) {
_stopCompleter.complete();
}
} else if (type == 'session.created') {
String id = msg['s'];
_remoteSessions[id] = _WorkerSession(this, id, false, msg['n']);
_sendPort.send({'t': 'session.ready', 's': id});
_sessionController.add(_remoteSessions[id]!);
} else if (type == 'session.ready') {
String id = msg['s'];
if (_sessionReady.containsKey(id)) {
_sessionReady[id]?.complete();
_sessionReady.remove(id);
}
} else if (type == 'session.data') {
String id = msg['s'];
if (_ourSessions.containsKey(id)) {
(_ourSessions[id] as _WorkerSession)._messages.add(msg['d']);
} else if (_remoteSessions.containsKey(id)) {
(_remoteSessions[id] as _WorkerSession)._messages.add(msg['d']);
}
} else if (type == 'session.done') {
String id = msg['s'];
if (_ourSessions.containsKey(id)) {
var c = (_ourSessions[id] as _WorkerSession)._doneCompleter;
if (!c.isCompleted) {
c.complete();
}
_ourSessions.remove(id);
} else if (_remoteSessions.containsKey(id)) {
var c = (_remoteSessions[id] as _WorkerSession)._doneCompleter;
if (!c.isCompleted) {
c.complete();
}
_remoteSessions.remove(id);
}
} else {
throw Exception('Unknown message: $msg');
}
}