Skip to content

Realm usage rules

Dean Herbert edited this page Jun 24, 2021 · 5 revisions

Realm is intended to keep threading and consistency management simple for the developer. This constrains how we can make use of realm, likely for the best. As such, there are a few best practices (or workarounds) required to get the flexibility we require from database bound entities:

Consuming from the update thread

  • If you need temporary access to data from the update thread, access and directly interact with IRealmFactory.Context however you wish. This is a context always maintained on the update thread, getting refreshed each update frame.
  • If you need to bind to property/value changed and keep track of queries RealmObjects, use Live<T> (see below).

Consuming from an async thread (ie. inside of BackgroundDependencyLoader methods)

  • If you need temporary access to data (which is resolved to members which are not managed, ie. strings being pulled out of a RealmObject) use using (var context = IRealmFactory.GetForRead()). Never keep this context open beyond the local usage.
  • If you need to keep the RealmObjects around for use on the update thread in the future, in addition to a local context, use Live<T> (see below).

Modifying data

using (var usage = realmFactory.GetForWrite())
{
    var binding = usage.Realm.Find<RealmKeyBinding>(((IHasGuidPrimaryKey)button.KeyBinding).ID);
    binding.KeyCombinationString = button.KeyBinding.KeyCombinationString;

    usage.Commit();
}