typedef FEventCallback<T> = void Function(Object sender, T e);

class FEventHandler<T> {
  List<FEventCallback<T>>? _callbacks;
  bool _isDispoed = false;

  void emit(Object sender, T e) {
    if (_isDispoed) return;

    if (_callbacks != null && _callbacks!.isNotEmpty) {
      final cbsCopy = [..._callbacks!]; // 优化线程安全
      for (final callback in cbsCopy) {
        if (_callbacks?.contains(callback) == true) {
          callback.call(sender, e);
        }
      }
    }
  }

  void addListener(FEventCallback<T> callback) {
    if (_isDispoed) return;

    _callbacks ??= [];
    _callbacks!.add(callback);
  }

  void removeListener(FEventCallback<T> callback) {
    if (_isDispoed) return;
    if (_callbacks == null) return;

    if (_callbacks!.contains(callback)) {
      _callbacks!.remove(callback);
    }
  }

  void dispose() {
    _isDispoed = true;
    _callbacks?.clear();
    _callbacks = null;
  }
}
