A logical counter representation for performing numeric updates that need to be synchronized as sequentially consistent events rather than individual reassignments of the number.

For instance, offline Client 1 and Client 2 which both see Counter.value as 0, can both call Counter.increment(1). Once online, the value will converge to 2.

Counter types are not supported as:

  • Mixed values
  • Primary keys
  • Inside collections
  • Query arguments for placeholders (e.g. $0) in filtered()
    • If you need to use the value of the Counter when filtering, use Counter.value.

Declaring a counter

A property schema is declared as either:

  • "counter"
  • { type: "int", presentation: "counter" }

Creating a counter

Use a number when creating your counter on a Realm.Object.

realm.write(() => {
realm.create(MyObject, { _id: "123", counter: 0 });
});

Updating the count

Use the instance methods to update the underlying count.

Nullability

The above property schema can be extended to allow a nullable counter. A Counter never stores null values itself, but the counter property on the Realm.Object (e.g. myRealmObject.myCounter) can be null.

To create a counter from a previously null value, or to reset a nullable counter to null, use UpdateMode.Modified or UpdateMode.All.

realm.write(() => {
realm.create(MyObject, { _id: "123", counter: 0 }, UpdateMode.Modified);
});

Constructors

Accessors

Methods

Constructors

Accessors

  • get value(): number
  • The current count.

    Returns number

Methods

  • Decrement the count.

    Parameters

    • Optional by: number

      The value to decrement by. (Default: 1)

    Returns void

  • Increment the count.

    Parameters

    • Optional by: number

      The value to increment by. (Default: 1)

    Returns void

  • Reset the count.

    Parameters

    • value: number

      The value to reset the count to.

    Returns void

    Warning

    Unlike increment and decrement, setting the count behaves like regular individual updates to the underlying value.

Generated using TypeDoc