Skip to main content
Version: v1

SharedCounter Class

A SharedCounter is a shared object which holds a number that can be incremented or decremented.

Signature

export declare class SharedCounter extends SharedObject<ISharedCounterEvents> implements ISharedCounter

Extends: SharedObject<ISharedCounterEvents

Implements: ISharedCounter

Remarks

### Creation

To create a SharedCounter, get the factory and call create with a runtime and string ID:

const factory = SharedCounter.getFactory();
const counter = factory.create(this.runtime, id) as SharedCounter;

### Usage

Once created, you can call increment to modify the value with either a positive or negative number:

counter.increment(10); // add 10 to the counter value
counter.increment(-5); // subtract 5 from the counter value

To observe changes to the value (including those from remote clients), register for the "incremented" event:

counter.on("incremented", (incrementAmount, newValue) => {
console.log(`The counter incremented by ${incrementAmount} and now has a value of ${newValue}`);
});

Constructors

Constructor Description
(constructor)(id, runtime, attributes) Constructs a new instance of the SharedCounter class

Static Methods

Method Return Type Description
create(runtime, id) SharedCounter Create a new shared counter
getFactory() IChannelFactory Get a factory for SharedCounter to register with the data store.

Properties

Property Type Description
value number The counter value.

Methods

Method Return Type Description
increment(incrementAmount) void Increments or decrements the value. Must only increment or decrement by a whole number value.

Constructor Details

(constructor)

Constructs a new instance of the SharedCounter class

Signature

constructor(id: string, runtime: IFluidDataStoreRuntime, attributes: IChannelAttributes);

Parameters

Parameter Type Description
id string
runtime IFluidDataStoreRuntime
attributes IChannelAttributes

Property Details

value

The counter value.

Signature

get value(): number;

Type: number

Method Details

create

Create a new shared counter

Signature

static create(runtime: IFluidDataStoreRuntime, id?: string): SharedCounter;

Parameters

Parameter Modifiers Type Description
runtime IFluidDataStoreRuntime data store runtime the new shared counter belongs to
id optional string optional name of the shared counter

Returns

newly create shared counter (but not attached yet)

Return type: SharedCounter

getFactory

Get a factory for SharedCounter to register with the data store.

Signature

static getFactory(): IChannelFactory;

Returns

a factory that creates and load SharedCounter

Return type: IChannelFactory

increment

Increments or decrements the value. Must only increment or decrement by a whole number value.

Signature

increment(incrementAmount: number): void;

Parameters

Parameter Type Description
incrementAmount number a whole number to increment or decrement by.