ZenQuery<T> constructor

ZenQuery<T>({
  1. required Object queryKey,
  2. required ZenQueryFetcher<T> fetcher,
  3. ZenQueryConfig? config,
  4. T? initialData,
  5. ZenScope? scope,
  6. bool autoDispose = true,
  7. bool registerInCache = true,
  8. bool enabled = true,
})

Implementation

ZenQuery({
  required Object queryKey,
  required this.fetcher,
  ZenQueryConfig? config,
  this.initialData,
  this.scope,
  this.autoDispose = true,
  bool registerInCache = true,
  bool enabled = true,
})  : queryKey = QueryKey.normalize(queryKey),
      config = ZenQueryConfig.defaults.merge(config).cast<T>(),
      _registerInCache = registerInCache,
      enabled = RxBool(enabled) {
  // Set initial data if provided
  if (initialData != null) {
    data.value = initialData;
    status.value = ZenQueryStatus.success;
    // Don't set _lastFetchTime here - initial data should be considered stale
    // so that the first fetch() actually fetches fresh data
    _lastFetchTime = null;
  } else if (this.config.placeholderData != null) {
    data.value = this.config.placeholderData;
    status.value = ZenQueryStatus.success;
    isPlaceholderData.value = true;
  }

  // Register in cache (scope-aware or global)
  if (_registerInCache) {
    if (scope != null) {
      _registerInScope();
    } else {
      ZenQueryCache.instance.register(this);
    }
  }

  // Setup background refetch if enabled
  _setupBackgroundRefetch();

  // Setup enabled listener
  ZenWorkers.ever(this.enabled, (isEnabled) {
    if (isEnabled && !_isDisposed) {
      // When re-enabled, fetch if stale or idle
      if (isStale || status.value == ZenQueryStatus.idle) {
        fetch().then((_) {}, onError: (_) {});
      }
    }
  });

  _initData();
}