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​

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

Static Methods​

MethodReturn TypeDescription
create(runtime, id)SharedCounterCreate a new shared counter
getFactory()IChannelFactoryGet a factory for SharedCounter to register with the data store.

Properties​

PropertyTypeDescription
valuenumberThe counter value.

Methods​

MethodReturn TypeDescription
increment(incrementAmount)voidIncrements 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​

ParameterTypeDescription
idstring
runtimeIFluidDataStoreRuntime
attributesIChannelAttributes

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​

ParameterModifiersTypeDescription
runtimeIFluidDataStoreRuntimedata store runtime the new shared counter belongs to
idoptionalstringoptional 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​

ParameterTypeDescription
incrementAmountnumbera whole number to increment or decrement by.