# SubscriptionManager

```typescript
class SubscriptionManager<S extends SubscriptionConstructable> implements Manager
```

Orchestrates all subscriptions; ensuring fresh data without overfetching.

> **Info: implements**
>
> `SubscriptionManager` implements [Manager](https://dataclient.io/docs/api/Manager.md)

## constructor(Subscription: S)

[Subscription](#subscription) is the class that will be used to handle subscriptions to each endpoint.
Each instance represents one subscription to a specific unique endpoint.

## Consumed Actions

- 'rdc/subscribe'
- 'rdc/unsubscribe'

## Subscription

`Subscription` is a class that implements `SubscriptionConstructable`. `Subscription` instances
handle the actual subscriptions.

```typescript
/** Interface handling a single resource subscription */
interface Subscription {
  add(frequency?: number): void;
  remove(frequency?: number): boolean;
  cleanup(): void;
  init?(): void;
}

/** The static class that constructs Subscription */
export interface SubscriptionConstructable {
  new (
    action: Omit<SubscribeAction, 'type'>,
    controller: Controller,
  ): Subscription;
}
```

### add(frequency?: number): void

Adds a new subscription at the provided frequency for the resource.

### remove(frequency?: number): boolean

Removes a subscription for the given frequency. Returns `true` if there are no
more subscriptions after. This is used to clean up unused `Subscription`s.

### cleanup(): void

Stops background work, like timers or connections. `SubscriptionManager` calls it when the Subscription is no longer
in use, and when the store pauses.

### init?(): void

Resumes background work that `cleanup()` stopped. `SubscriptionManager` calls it when the store resumes, for every
Subscription it still tracks. It must do nothing while the Subscription is already running. Without `init()`, a
Subscription that outlives a pause stays stopped.

### Included implementation

- [PollingSubscription](https://dataclient.io/docs/api/PollingSubscription.md)

> **Note**
>
> Implementing your own `Subscription` to handle websockets can be done by
> [dispatching](https://dataclient.io/docs/api/Controller.md#set) `rdc/set` actions with the data it gets to update.
> Be sure to handle connection opening in the constructor, close the connection
> in `cleanup()`, and reopen it in `init()`
