Add realm factory helper methods to run work on the correct context

Avoids constructing a new `Realm` instance when called from the update
thread without worrying about disposal.
This commit is contained in:
Dean Herbert 2022-01-21 01:33:45 +09:00
parent 1a20725162
commit 0c9eb3ad61
1 changed files with 35 additions and 0 deletions

View File

@ -169,6 +169,41 @@ private void cleanupPendingDeletions()
/// <returns></returns>
public bool Compact() => Realm.Compact(getConfiguration());
/// <summary>
/// Run work on realm with a return value.
/// </summary>
/// <remarks>
/// Handles correct context management automatically.
/// </remarks>
/// <param name="action">The work to run.</param>
/// <typeparam name="T">The return type.</typeparam>
public T Run<T>(Func<Realm, T> action)
{
if (ThreadSafety.IsUpdateThread)
return action(Context);
using (var realm = CreateContext())
return action(realm);
}
/// <summary>
/// Run work on realm.
/// </summary>
/// <remarks>
/// Handles correct context management automatically.
/// </remarks>
/// <param name="action">The work to run.</param>
public void Run(Action<Realm> action)
{
if (ThreadSafety.IsUpdateThread)
action(Context);
else
{
using (var realm = CreateContext())
action(realm);
}
}
public Realm CreateContext()
{
if (isDisposed)