diff --git a/lib/src/hermes_base.dart b/lib/src/hermes_base.dart index 8fb1a5b..2fdc333 100644 --- a/lib/src/hermes_base.dart +++ b/lib/src/hermes_base.dart @@ -33,51 +33,28 @@ * */ -import 'dart:collection'; +import 'dart:async'; -/// [Hermes]. The messenger. class Hermes { - final Map> _callbacks = - >{}; - - static Map _instances = {}; - + static final _instances = {}; + Hermes._(); - static Hermes _get() { - if (!_instances.containsKey(T.hashCode)) { - _instances[T.hashCode] = Hermes._(); - } - return _instances[T.hashCode] as Hermes; - } - - /// [send] allows to send a message. + /// [send] will send a message to the stream linked to the type. + /// + /// Returns true if the target exists, false otherwise static bool send(T message) { - var i = _get(); - - if (!i._callbacks.containsKey(T.hashCode)) { - return false; - } - - for (var handler in i._callbacks[T.hashCode]) { - Future.microtask(() { - handler(message); - }); - } - ; - - return true; + final target = _instances[T]; + final?.add(message); + return final != null; } /// [fetch] registers callbacks for messages. /// /// whenever a message of type [T] is received, the [callback] /// is called. - static fetch(Function(T arg) callback) { - var i = _get(); - if (!i._callbacks.containsKey(T.hashCode)) { - i._callbacks[T.hashCode] = Queue(); - } - i._callbacks[T.hashCode].add(callback); + static void fetch(Function(T arg) callback) { + final target = _instances[T] ??= StreamController.broadcast(); + (target as StreamController).stream.listen(callback); } }