Counters - Android SDK¶
On this page
Realm Database offers MutableRealmInteger, a wrapper around numeric values, to help better synchronize numeric changes across multiple clients.
Typically, incrementing or decrementing a
long field of a Realm
object looks something like this:
- Read the current value of the field.
- Update that value in memory to a new value based on the increment or decrement.
- Write a new value back to the field.
When multiple distributed clients attempt this at the same time,
updates reaching clients in different orders can
result in different values on different clients.
improves on this by translating numeric updates into sync operations
that can be executed in any order to converge to the same value.
MutableRealmInteger fields are backed by traditional numeric types,
so no migration is required when changing a field from
The following example demonstrates a
MutableRealmInteger field that
counts the number of ghosts found in a haunted house:
MutableRealmInteger is a live object like
RealmList. This means the value contained
MutableRealmInteger can change when a realm is
written to. For this reason
MutableRealmInteger fields must be
To change a MutableRealmInteger value, call
decrement() within a write transaction:
You can assign a
MutableRealmInteger a new value with a call to
within a write transaction.
set() operator with extreme care.
the effects of any prior calls to
Although the value of a
MutableRealmInteger always converges
across devices, the specific value on which it converges depends on
the actual order in which operations took place.
not advised unless fuzzy counting is acceptable.
MutableRealmInteger instances retain a reference to their
parent object, neither object can be garbage collected while you still
retain a reference to the