Realm offers RealmInteger as a special integer type you can use as a logical counter. RealmInteger<T>
exposes an additional API that can more clearly express intent and generate better conflict resolution steps when using Synchronized Realms. The type argument <T>
can be of type byte
, short
, int
, or long
. The following example shows how to use a RealmInteger
property that maps to an int
:
public partial class MyRealmClass : IRealmObject{ [PrimaryKey] public int _id { get; set; } public RealmInteger<int> Counter { get; set; }}
Traditionally, you would implement a counter by reading a value, incrementing it, and then setting it (myObject.Counter += 1
). This does not work well in an asynchronous situation like when two clients are offline. Consider the following scenario:
The realm object has a counter
property of type int
. It is currently set to a value of 10
.
Clients 1 and 2 both read the counter
property (10
) and each increments the value by 1
.
When each client regains connectivity and merges their changes, they expect a value of 11, and there is no conflict. However, the counter value should be 12
!
When using a RealmInteger
, however, you can call the Increment()
and Decrement()
methods, and to reset the counter, you set it to 0
, just as you would an int
:
var myObject = realm.Find<MyRealmClass>(id);realm.Write(() =>{ myObject.Counter.Increment(); myObject.Counter.Increment(5); myObject.Counter.Decrement(); myObject.Counter.Increment(-3); myObject.Counter = 0; int bar = myObject.Counter;});
Important
When you reset a RealmInteger
, you may run into the offline merge issue described above.
A RealmInteger
is backed by traditional integer
type, so no schema migration is required when changing a property type from T
to RealmInteger<T>
.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4