cleanupAllScopesExcept static method

void cleanupAllScopesExcept(
  1. String keepScopeName
)

Clean up all scopes except the specified one and the root scope This is called when a route with useParentScope=false is created or popped back to

Implementation

static void cleanupAllScopesExcept(String keepScopeName) {
  if (ZenConfig.enableDebugLogs) {
    ZenLogger.logDebug('๐Ÿงน Cleaning up all scopes except: $keepScopeName');
  }

  // Get all scopes to clean up (exclude root scope and the one to keep)
  final scopesToCleanup = <String>[];

  // Add persistent scopes (excluding root and the one to keep)
  for (final scopeName in _persistentScopes.keys) {
    if (scopeName != keepScopeName && scopeName != 'RootScope') {
      scopesToCleanup.add(scopeName);
    }
  }

  // Add auto-dispose scopes (excluding the one to keep)
  for (final scopeName in _autoDisposeScopes.keys) {
    if (scopeName != keepScopeName) {
      scopesToCleanup.add(scopeName);
    }
  }

  if (ZenConfig.enableDebugLogs) {
    ZenLogger.logDebug('๐Ÿงน Scopes to cleanup: ${scopesToCleanup.join(', ')}');
  }

  // Clean up each scope
  for (final scopeName in scopesToCleanup) {
    try {
      // Remove from explicitly persistent if it was there
      _explicitlyPersistentScopes.remove(scopeName);

      // Force dispose the scope
      final persistentScope = _persistentScopes.remove(scopeName);
      final autoDisposeScope = _autoDisposeScopes.remove(scopeName);

      final scope = persistentScope ?? autoDisposeScope;
      if (scope != null && !scope.isDisposed) {
        scope.dispose();
        if (ZenConfig.enableDebugLogs) {
          ZenLogger.logDebug('๐Ÿ—‘๏ธ Disposed scope during cleanup: $scopeName');
        }
      }

      // Remove from all tracking
      _removeScopeFromTracking(scopeName);
    } catch (e, stackTrace) {
      ZenLogger.logError('Error cleaning up scope $scopeName', e, stackTrace);
    }
  }

  if (ZenConfig.enableDebugLogs) {
    ZenLogger.logDebug(
        'โœ… Cleanup complete. Remaining scopes: ${_getAllScopeNames().join(', ')}');
  }
}