Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use streams because this is literally just a stream recreation #1

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 12 additions & 35 deletions lib/src/hermes_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,51 +33,28 @@
*
*/

import 'dart:collection';
import 'dart:async';

/// [Hermes]. The messenger.
class Hermes<T> {
final Map<int, ListQueue<Function(T)>> _callbacks =
<int, ListQueue<Function(T)>>{};

static Map<int, Hermes> _instances = <int, Hermes>{};

static final _instances = <Type, StreamController>{};

Hermes._();

static Hermes<T> _get<T>() {
if (!_instances.containsKey(T.hashCode)) {
_instances[T.hashCode] = Hermes<T>._();
}
return _instances[T.hashCode] as Hermes<T>;
}

/// [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>(T message) {
var i = _get<T>();

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<T>(Function(T arg) callback) {
var i = _get<T>();
if (!i._callbacks.containsKey(T.hashCode)) {
i._callbacks[T.hashCode] = Queue<Function(T)>();
}
i._callbacks[T.hashCode].add(callback);
static void fetch<T>(Function(T arg) callback) {
final target = _instances[T] ??= StreamController<T>.broadcast();
(target as StreamController<T>).stream.listen(callback);
}
}