RxComputed<T> constructor

RxComputed<T>(
  1. T computation()
)

Implementation

factory RxComputed(T Function() computation) {
  final trackedDeps = <ValueNotifier>{};

  RxTracking.setTrackerWithoutRebuild((notifier) {
    trackedDeps.add(notifier);
  });

  late T initialValue;
  RxException? initError;

  try {
    initialValue = computation();
  } catch (e, stack) {
    initError = RxException.withTimestamp(
      'Error in computed value initialization',
      originalError: e,
      stackTrace: stack,
    );
    rethrow;
  } finally {
    RxTracking.clearTracker();
  }

  final instance = RxComputed._(initialValue, computation);
  instance._lastError = initError;

  for (final dep in trackedDeps) {
    instance._dependencies.add(dep);
    dep.addListener(instance._onDependencyChanged);
  }

  return instance;
}