runAsync<T> method

Future<void> runAsync<T>(
  1. ZenithNode<AsyncValue<T>> node,
  2. Future<T> task()
)

Safely runs an async task and writes its result to node, guarding every mutation with this ref's mounted state.

Sets node to AsyncLoading (preserving any previous data) before awaiting task, then to AsyncData on success or AsyncError on failure — but only if this ref is still mounted at each step. This eliminates the need for manual if (!ref.isMounted) return; checks after async boundaries.

Implementation

Future<void> runAsync<T>(
  ZenithNode<AsyncValue<T>> node,
  Future<T> Function() task,
) async {
  if (!_isMounted) return;
  node.set(AsyncLoading<T>(node.value.valueOrNull));

  try {
    final data = await task();
    if (!_isMounted) return;
    node.set(AsyncData<T>(data));
  } catch (error, stackTrace) {
    if (!_isMounted) return;
    node.set(AsyncError<T>(error, stackTrace));
  }
}