Skip to content

Proposal: add param1 to registerHandler and watchValue #46

Description

@Feichtmeier

When creating cached factories with factory params that include commands it would be great to use the registerHandler and watchValue functions just like with singletons.

In case of watchValue this is probbaly only convenience since one could use watch functions, but as far as I understand it the registerHandler miss a way to pick a specific instance by param1.

void registerHandler<T extends Object, R>({
  ValueListenable<R> Function(T)? select,
  required void Function(
          BuildContext context, R newValue, void Function() cancel)
      handler,
  T? target,
  bool allowObservableChange = false,
  bool executeImmediately = false,
  String? instanceName,
  dynamic? param1,
  GetIt? getIt,
}) {
  assert(_activeWatchItState != null,
      'registerHandler can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');

  final getItInstance = getIt ?? di;
  final parentObject = target ?? getItInstance<T>(instanceName: instanceName, param1: param1);

  // Validate target type when no select function is provided
  if (select == null && parentObject is! Listenable) {
    throw ArgumentError(
        'When no select function is provided, target must be a Listenable. '
        'Got: ${parentObject.runtimeType}');
  }

  _activeWatchItState!.watchListenable<T, R>(
    parentOrListenable: parentObject,
    selector: select,
    allowObservableChange: allowObservableChange,
    handler: handler,
    executeImmediately: executeImmediately,
  );
}
R watchValue<T extends Object, R>(
  ValueListenable<R> Function(T) selectProperty, {
  bool allowObservableChange = false,
  String? instanceName,
  dynamic? param1,
  GetIt? getIt,
}) {
  assert(_activeWatchItState != null,
      'watchValue can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');
  final getItInstance = getIt ?? di;
  final parentObject = getItInstance<T>(instanceName: instanceName, param1: param1);
  final observedObject = _activeWatchItState!.watchListenable<T, R>(
    parentOrListenable: parentObject,
    selector: selectProperty,
    allowObservableChange: allowObservableChange,
  );

  // Get the value from the returned observable (selector only called once!)
  return (observedObject as ValueListenable<R>).value;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions