89 lines
No EOL
2 KiB
Dart
89 lines
No EOL
2 KiB
Dart
|
|
// ignore_for_file: prefer_final_fields
|
|
|
|
import 'package:protobuf/protobuf.dart';
|
|
|
|
abstract class Communicator
|
|
{
|
|
Map<String, IDataHandler> _handlerDic = {};
|
|
late Map<String, GeneratedMessage Function(List<int>)> _instanceGenerator;
|
|
|
|
Communicator();
|
|
|
|
void initialize(Map<String, GeneratedMessage Function(List<int>)> instanceGenerator)
|
|
{
|
|
_instanceGenerator = instanceGenerator;
|
|
}
|
|
|
|
T Function(List<int>) getGenerator<T extends GeneratedMessage>(String type)
|
|
{
|
|
if(!_instanceGenerator.containsKey(type))
|
|
{
|
|
throw Exception('Must set protobuf packet creator before use it.');
|
|
}
|
|
return _instanceGenerator[type] as T Function(List<int>);
|
|
}
|
|
|
|
Future send<T extends GeneratedMessage>(T data);
|
|
|
|
void onReceivedData(String typeName, List<int> data)
|
|
{
|
|
if( _handlerDic.containsKey(typeName) ) {
|
|
_handlerDic[typeName]?.onMessage(data);
|
|
}
|
|
}
|
|
|
|
void addListener<T extends GeneratedMessage>(void Function(T) listener)
|
|
{
|
|
var type = T.toString();
|
|
if(!_handlerDic.containsKey(type))
|
|
{
|
|
_handlerDic[type] = DataHandler<T>(getGenerator(type));
|
|
}
|
|
var handler = _handlerDic[type] as DataHandler<T>;
|
|
handler.addListener(listener);
|
|
}
|
|
|
|
void removeListener<T extends GeneratedMessage>(void Function(T) listener)
|
|
{
|
|
var type = T.toString();
|
|
if(_handlerDic.containsKey(type))
|
|
{
|
|
var handler = _handlerDic[type] as DataHandler<T>;
|
|
handler.removeListener(listener);
|
|
}
|
|
}
|
|
}
|
|
|
|
abstract class IDataHandler
|
|
{
|
|
void onMessage(List<int> data);
|
|
}
|
|
|
|
class DataHandler<T extends GeneratedMessage> implements IDataHandler
|
|
{
|
|
T Function(List<int>) _generator;
|
|
List<void Function(T)> _listeners = [];
|
|
|
|
DataHandler(this._generator);
|
|
|
|
@override
|
|
void onMessage(List<int> data)
|
|
{
|
|
for(var listener in _listeners)
|
|
{
|
|
listener.call(_generator(data));
|
|
}
|
|
}
|
|
|
|
void addListener(void Function(T) handler)
|
|
{
|
|
removeListener(handler); //중복 리스너 불허
|
|
_listeners.add(handler);
|
|
}
|
|
|
|
void removeListener(void Function(T) handler)
|
|
{
|
|
_listeners.remove(handler);
|
|
}
|
|
} |