osu/osu.Game/Database/RealmExtensions.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

77 lines
2.5 KiB
C#
Raw Normal View History

2021-01-11 09:58:56 +00:00
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
2021-01-11 09:58:56 +00:00
using Realms;
namespace osu.Game.Database
{
public static class RealmExtensions
{
/// <summary>
/// Perform a write operation against the provided realm instance.
/// </summary>
/// <remarks>
/// This will automatically start a transaction if not already in one.
/// </remarks>
/// <param name="realm">The realm to operate on.</param>
/// <param name="function">The write operation to run.</param>
public static void Write(this Realm realm, Action<Realm> function)
2021-01-11 09:58:56 +00:00
{
Transaction? transaction = null;
2022-07-07 09:15:15 +00:00
try
{
if (!realm.IsInTransaction)
transaction = realm.BeginWrite();
2022-07-07 09:15:15 +00:00
function(realm);
2022-07-07 09:15:15 +00:00
transaction?.Commit();
}
finally
{
transaction?.Dispose();
}
}
/// <summary>
/// Perform a write operation against the provided realm instance.
/// </summary>
/// <remarks>
/// This will automatically start a transaction if not already in one.
/// </remarks>
/// <param name="realm">The realm to operate on.</param>
/// <param name="function">The write operation to run.</param>
public static T Write<T>(this Realm realm, Func<Realm, T> function)
2021-01-11 09:58:56 +00:00
{
Transaction? transaction = null;
2022-07-07 09:15:15 +00:00
try
{
if (!realm.IsInTransaction)
transaction = realm.BeginWrite();
2022-07-07 09:15:15 +00:00
var result = function(realm);
2022-07-07 09:15:15 +00:00
transaction?.Commit();
2022-07-07 09:15:15 +00:00
return result;
}
finally
{
transaction?.Dispose();
}
2021-01-11 09:58:56 +00:00
}
/// <summary>
/// Whether the provided change set has changes to the top level collection.
/// </summary>
/// <remarks>
/// Realm subscriptions fire on both collection and property changes (including *all* nested properties).
/// Quite often we only care about changes at a collection level. This can be used to guard and early-return when no such changes are in a callback.
/// </remarks>
public static bool HasCollectionChanges(this ChangeSet changes) => changes.InsertedIndices.Length > 0 || changes.DeletedIndices.Length > 0 || changes.Moves.Length > 0;
2021-01-11 09:58:56 +00:00
}
}