> ## Documentation Index
> Fetch the complete documentation index at: https://docs-unity.molca.id/llms.txt
> Use this file to discover all available pages before exploring further.

# DataManager

> Networked data providers, caching, model subscriptions, and batch data processing.

**File:** `Packages/com.molca.core/Runtime/Networking/Data/DataManager.cs`

## When to use

Use `DataManager` instead of one-off `HttpClient` calls when you need:

* **Persistent data providers** that continuously feed data (HTTP polling, SSE, WebSocket patterns).
* **Centralized caching** with configurable duration and max size per provider.
* **Model subscriptions** — get notified when new data arrives for a specific `DataModel`, with automatic batching to reduce callback frequency.
* **Multiple data sources** coordinated through a single gateway with provider registration/deregistration.

For simple one-shot API calls, prefer [HttpClient](/core/http-client) directly.

## API

### Provider management

| Method                   | Signature                                            | Description                                  |
| ------------------------ | ---------------------------------------------------- | -------------------------------------------- |
| `RegisterDataProvider`   | `void RegisterDataProvider(DataProvider provider)`   | Register a provider and initialize its cache |
| `UnregisterDataProvider` | `void UnregisterDataProvider(DataProvider provider)` | Remove a provider and its cache              |
| `GetProvider`            | `DataProvider GetProvider(string providerId)`        | Get a registered provider by ID              |
| `IsProviderActive`       | `bool IsProviderActive(string providerId)`           | Check if a provider is registered            |
| `GetProviderIds`         | `List<string> GetProviderIds()`                      | List all registered provider IDs             |

### Data subscription and access

| Method                     | Signature                                                                          | Description                                 |
| -------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------- |
| `SubscribeToDataModel`     | `void SubscribeToDataModel(DataModel model, Action<ImmutableData[]> callback)`     | Get batched notifications when data arrives |
| `UnsubscribeFromDataModel` | `void UnsubscribeFromDataModel(DataModel model, Action<ImmutableData[]> callback)` | Stop receiving notifications                |
| `GetAllData`               | `IReadOnlyList<ImmutableData> GetAllData(string providerId)`                       | Get cached data for a provider              |
| `FetchData`                | `bool FetchData(string providerId)`                                                | Manually trigger a data fetch               |
| `RefreshAllData`           | `void RefreshAllData()`                                                            | Refresh all active providers                |
| `IsDataStale`              | `bool IsDataStale(string providerId)`                                              | Check if cached data exceeds duration       |

**Events:** `OnDataUpdated`, `OnDataProviderRegistered`, `OnDataProviderUnregistered` (static `event Action`).

## Code

**Subscribe to model updates** (recommended for live data):

```csharp theme={null}
using Molca;
using Molca.Networking.Data;
using UnityEngine;

public class LiveModelBinder : MonoBehaviour
{
    [SerializeField] private DataModel targetModel;

    private async void Start()
    {
        await RuntimeManager.WaitForInitialization();
        DataManager.Instance?.SubscribeToDataModel(targetModel, OnDataReceived);
    }

    private void OnDestroy()
    {
        DataManager.Instance?.UnsubscribeFromDataModel(targetModel, OnDataReceived);
    }

    private void OnDataReceived(ImmutableData[] batch)
    {
        Debug.Log($"Received {batch.Length} items for model {targetModel.ModelName}");
        foreach (var data in batch)
        {
            // Process each data item
        }
    }
}
```

**Event-based** (for generic data change notifications):

```csharp theme={null}
private void OnEnable() => DataManager.OnDataUpdated += OnDataUpdated;
private void OnDisable() => DataManager.OnDataUpdated -= OnDataUpdated;

private void OnDataUpdated(string providerId, ImmutableData data)
{
    Debug.Log($"{providerId} updated");
}
```

Resolve the subsystem: **`DataManager.Instance`** (`RuntimeManager.GetSubsystem<DataManager>()`).

## API Reference

### Cache and data pool management

| Method                      | Signature                                                       | Description                                                               |
| --------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `GetProviderCache`          | `DataCache GetProviderCache(string providerId)`                 | Get the centralized cache for a specific provider                         |
| `GetOrCreateCache`          | `DataCache GetOrCreateCache(string cacheKey, DataModel model)`  | Get or create a cache for multi-mapping scenarios (e.g. Socket.IO events) |
| `GetAllProviderCaches`      | `IReadOnlyDictionary<string, DataCache> GetAllProviderCaches()` | Get all provider caches for external access/debugging                     |
| `ClearCache`                | `void ClearCache(string providerId)`                            | Clear cache for a specific provider                                       |
| `ClearAllCaches`            | `void ClearAllCaches()`                                         | Clear all provider caches                                                 |
| `GetCacheStats`             | `Dictionary<string, object> GetCacheStats()`                    | Get cache statistics for monitoring                                       |
| `GetProviderCacheStats`     | `object GetProviderCacheStats(string providerId)`               | Get cache stats for a specific provider                                   |
| `FlushAllDataPools`         | `void FlushAllDataPools()`                                      | Manually flush all data pools for immediate processing                    |
| `FlushDataPoolManually`     | `void FlushDataPoolManually(string modelId)`                    | Flush a specific data pool by model ID                                    |
| `TriggerPeriodicFlushCheck` | `void TriggerPeriodicFlushCheck()`                              | Manually trigger the periodic flush check                                 |
| `GetDataPoolStatus`         | `Dictionary<string, object> GetDataPoolStatus()`                | Get current data pool status for monitoring                               |

### Utility methods

| Method                             | Signature                                                               | Description                                               |
| ---------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------- |
| `GetProviderModel`                 | `DataModel GetProviderModel(string providerId)`                         | Get the data model for a specific provider                |
| `GetAlwaysIncludedProvidersStatus` | `Dictionary<string, bool> GetAlwaysIncludedProvidersStatus()`           | Get registration status of always-included providers      |
| `GetDataModelSubscriptionStats`    | `Dictionary<string, int> GetDataModelSubscriptionStats()`               | Get active subscription counts by model                   |
| `HasActiveSubscriptions`           | `bool HasActiveSubscriptions(DataModel dataModel)`                      | Check if a DataModel has active subscriptions             |
| `AddTestDataToProvider`            | `bool AddTestDataToProvider(string providerId, ImmutableData testData)` | Manually add test data (useful for testing subscriptions) |

## Troubleshooting

* **Subscribed but no callbacks firing:** verify the `DataModel.ModelId` matches between the provider's mapping and your subscription. Enable `DataConfig.LogDataOperations` to see subscription/flush logs.
* **Data arrives but view is stale:** `DataManager` batches data into pools flushed every \~100ms. Call `FlushAllDataPools()` if you need immediate processing. Also confirm you're subscribing to the correct `DataModel` instance.
* **Provider not found:** `RegisterDataProvider` must be called before `FetchData`. Check that the provider's `ProviderId` matches and the mapping / `DataModel` is assigned.
* **Cache grows unbounded:** configure `DefaultMaxCacheSize` and `DefaultCacheDuration` on the `DataConfig` module in [Global Settings](/setup/global-settings).

## Related

* [HttpClient](/core/http-client) — underlying transport for HTTP-based providers
* [Global Settings](/setup/global-settings) — `DataConfig` module for cache and logging settings
* [EventDispatcher](/core/event-dispatcher) — alternative pub/sub for simple notifications
* [Recipe: Integrate HTTP requests with data persistence](/recipes/integrate-http-data-persistence) — step-by-step guide to combining HttpClient and DataManager for API calls with local caching

## Unity Editor

<Frame caption="DataManager module configuration">
  <img src="https://mintcdn.com/ptmolcateknologinusantara/jWDWJqZnZidoWqQK/images/features/core/data-manager-inspector.png?fit=max&auto=format&n=jWDWJqZnZidoWqQK&q=85&s=e434648b5502ed1c67fa127216c79d22" alt="Data Manager Inspector" width="506" height="225" data-path="images/features/core/data-manager-inspector.png" />
</Frame>
