-
Notifications
You must be signed in to change notification settings - Fork 157
/
CollectionExtensions.cs
340 lines (306 loc) · 18.1 KB
/
CollectionExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Realms.Helpers;
namespace Realms
{
/// <summary>
/// A set of extensions methods exposing notification-related functionality over collections.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class CollectionExtensions
{
/// <summary>
/// A convenience method that casts <see cref="IQueryable{T}"/> to <see cref="IRealmCollection{T}"/> which
/// implements <see cref="INotifyCollectionChanged"/>.
/// </summary>
/// <param name="query">The <see cref="IQueryable{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the <see cref="RealmObject"/> or <see cref="EmbeddedObject"/> in the results.</typeparam>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
/// <returns>The collection, implementing <see cref="INotifyCollectionChanged"/>.</returns>
public static IRealmCollection<T> AsRealmCollection<T>(this IQueryable<T> query)
where T : RealmObjectBase
{
Argument.NotNull(query, nameof(query));
if (query is IRealmCollection<T> collection)
{
return collection;
}
throw new ArgumentException($"{nameof(query)} must be an instance of IRealmCollection<{typeof(T).Name}>.", nameof(query));
}
/// <summary>
/// A convenience method that casts <see cref="IQueryable{T}"/> to <see cref="IRealmCollection{T}"/> and subscribes for change notifications.
/// </summary>
/// <param name="results">The <see cref="IQueryable{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the <see cref="RealmObject"/> or <see cref="EmbeddedObject"/> in the results.</typeparam>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
/// <param name="callback">The callback to be invoked with the updated <see cref="IRealmCollection{T}"/>.</param>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
public static IDisposable SubscribeForNotifications<T>(this IQueryable<T> results, NotificationCallbackDelegate<T> callback)
where T : RealmObjectBase
{
return results.AsRealmCollection().SubscribeForNotifications(callback);
}
/// <summary>
/// A convenience method that casts <see cref="ISet{T}"/> to <see cref="IRealmCollection{T}"/> which implements
/// <see cref="INotifyCollectionChanged"/>.
/// </summary>
/// <param name="set">The <see cref="ISet{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the set.</typeparam>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
/// <returns>The collection, implementing <see cref="INotifyCollectionChanged"/>.</returns>
public static IRealmCollection<T> AsRealmCollection<T>(this ISet<T> set)
{
Argument.NotNull(set, nameof(set));
if (set is IRealmCollection<T> collection)
{
return collection;
}
throw new ArgumentException($"{nameof(set)} must be an instance of IRealmCollection<{typeof(T).Name}>.", nameof(set));
}
/// <summary>
/// A convenience method that casts <see cref="ISet{T}"/> to <see cref="IRealmCollection{T}"/> and subscribes for change notifications.
/// </summary>
/// <param name="set">The <see cref="ISet{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the set.</typeparam>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
/// <param name="callback">The callback to be invoked with the updated <see cref="IRealmCollection{T}"/>.</param>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
public static IDisposable SubscribeForNotifications<T>(this ISet<T> set, NotificationCallbackDelegate<T> callback) => set.AsRealmCollection().SubscribeForNotifications(callback);
/// <summary>
/// A convenience method that casts <see cref="IList{T}"/> to <see cref="IRealmCollection{T}"/> which implements
/// <see cref="INotifyCollectionChanged"/>.
/// </summary>
/// <param name="list">The <see cref="IList{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the list.</typeparam>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
/// <returns>The collection, implementing <see cref="INotifyCollectionChanged"/>.</returns>
public static IRealmCollection<T> AsRealmCollection<T>(this IList<T> list)
{
Argument.NotNull(list, nameof(list));
if (list is IRealmCollection<T> collection)
{
return collection;
}
throw new ArgumentException($"{nameof(list)} must be an instance of IRealmCollection<{typeof(T).Name}>.", nameof(list));
}
/// <summary>
/// A convenience method that casts <see cref="IList{T}"/> to <see cref="IRealmCollection{T}"/> and subscribes for change notifications.
/// </summary>
/// <param name="list">The <see cref="IList{T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the list.</typeparam>
/// <seealso cref="IRealmCollection{T}.SubscribeForNotifications"/>
/// <param name="callback">The callback to be invoked with the updated <see cref="IRealmCollection{T}"/>.</param>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
public static IDisposable SubscribeForNotifications<T>(this IList<T> list, NotificationCallbackDelegate<T> callback) => list.AsRealmCollection().SubscribeForNotifications(callback);
/// <summary>
/// Move the specified item to a new position within the list.
/// </summary>
/// <param name="list">The list where the move should occur.</param>
/// <param name="item">The item that will be moved.</param>
/// <param name="index">The new position to which the item will be moved.</param>
/// <typeparam name="T">Type of the objects in the list.</typeparam>
/// <remarks>
/// This extension method will work for standalone lists as well by calling <see cref="ICollection{T}.Remove"/>
/// and then <see cref="IList{T}.Insert"/>.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the index is less than 0 or greater than <see cref="ICollection{T}.Count"/> - 1.</exception>
public static void Move<T>(this IList<T> list, T item, int index)
{
Argument.NotNull(list, nameof(list));
var from = list.IndexOf(item);
list.Move(from, index);
}
/// <summary>
/// Move the specified item to a new position within the list.
/// </summary>
/// <param name="list">The list where the move should occur.</param>
/// <param name="from">The index of the item that will be moved.</param>
/// <param name="to">The new position to which the item will be moved.</param>
/// <typeparam name="T">Type of the objects in the list.</typeparam>
/// <remarks>
/// This extension method will work for standalone lists as well by calling <see cref="IList{T}.RemoveAt"/>
/// and then <see cref="IList{T}.Insert"/>.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the index is less than 0 or greater than <see cref="ICollection{T}.Count"/> - 1.</exception>
public static void Move<T>(this IList<T> list, int from, int to)
{
Argument.NotNull(list, nameof(list));
if (list is RealmList<T> realmList)
{
realmList.Move(from, to);
}
else
{
if (from < 0 || from >= list.Count)
{
throw new ArgumentOutOfRangeException(nameof(from));
}
if (to < 0 || to >= list.Count)
{
throw new ArgumentOutOfRangeException(nameof(to));
}
var item = list[from];
list.RemoveAt(from);
list.Insert(to, item);
}
}
/// <summary>
/// A convenience method that casts <see cref="IDictionary{String, T}"/> to <see cref="IRealmCollection{KeyValuePair}"/> which implements
/// <see cref="INotifyCollectionChanged"/>.
/// </summary>
/// <param name="dictionary">The <see cref="IDictionary{String, T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the dictionary.</typeparam>
/// <seealso cref="IRealmCollection{TValue}.SubscribeForNotifications"/>
/// <returns>The collection, implementing <see cref="INotifyCollectionChanged"/>.</returns>
public static IRealmCollection<KeyValuePair<string, T>> AsRealmCollection<T>(this IDictionary<string, T> dictionary)
{
Argument.NotNull(dictionary, nameof(dictionary));
if (dictionary is RealmDictionary<T> collection)
{
return collection;
}
throw new ArgumentException($"{nameof(dictionary)} must be an instance of IRealmCollection<KeyValuePair<string, {typeof(T).Name}>>.", nameof(dictionary));
}
/// <summary>
/// A convenience method that casts <see cref="IQueryable{T}"/> to <see cref="IRealmCollection{T}"/> and subscribes for change notifications.
/// </summary>
/// <param name="dictionary">The <see cref="IDictionary{String, T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the dictionary.</typeparam>
/// <seealso cref="IRealmCollection{TValue}.SubscribeForNotifications"/>
/// <param name="callback">The callback to be invoked with the updated <see cref="IRealmCollection{T}"/>.</param>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
public static IDisposable SubscribeForNotifications<T>(this IDictionary<string, T> dictionary, NotificationCallbackDelegate<KeyValuePair<string, T>> callback)
{
return dictionary.AsRealmCollection().SubscribeForNotifications(callback);
}
/// <summary>
/// A convenience method that casts <see cref="IQueryable{T}"/> to <see cref="IRealmCollection{T}"/> and subscribes for change notifications.
/// </summary>
/// <param name="dictionary">The <see cref="IDictionary{String, T}"/> to observe for changes.</param>
/// <typeparam name="T">Type of the elements in the dictionary.</typeparam>
/// <seealso cref="IRealmCollection{TValue}.SubscribeForNotifications"/>
/// <param name="callback">The callback to be invoked with the updated <see cref="IRealmCollection{T}"/>.</param>
/// <returns>
/// A subscription token. It must be kept alive for as long as you want to receive change notifications.
/// To stop receiving notifications, call <see cref="IDisposable.Dispose"/>.
/// </returns>
public static IDisposable SubscribeForKeyNotifications<T>(this IDictionary<string, T> dictionary, DictionaryNotificationCallbackDelegate<T> callback)
{
Argument.NotNull(dictionary, nameof(dictionary));
if (dictionary is RealmDictionary<T> collection)
{
return collection.SubscribeForKeyNotifications(callback);
}
throw new ArgumentException($"{nameof(dictionary)} must be an instance of IRealmCollection<KeyValuePair<string, {typeof(T).Name}>>.", nameof(dictionary));
}
/// <summary>
/// Apply an NSPredicate-based filter over a collection. It can be used to create
/// more complex queries, that are currently unsupported by the LINQ provider and
/// supports SORT and DISTINCT clauses in addition to filtering.
/// </summary>
/// <typeparam name="T">The type of the objects that will be filtered.</typeparam>
/// <param name="query">
/// A Queryable collection, obtained by calling <see cref="Realm.All{T}"/>.
/// </param>
/// <param name="predicate">The predicate that will be applied.</param>
/// <param name="arguments">Values used for substitution in the predicate. Note that all primitive types are accepted as they are implicitly converted to RealmValue.</param>
/// <returns>A queryable observable collection of objects that match the predicate.</returns>
/// <remarks>
/// This method can be used in combination with LINQ filtering, but it is strongly recommended
/// to avoid combining it if a <c>SORT</c> clause appears in the predicate.
/// <para/>
/// If you're not going to apply additional filters, it's recommended to use <see cref="AsRealmCollection{T}(IQueryable{T})"/>
/// after applying the predicate.
/// </remarks>
/// <example>
/// <code>
/// var results1 = realm.All<Foo>("Bar.IntValue > 0");
/// var results2 = realm.All<Foo>("Bar.IntValue > 0 SORT(Bar.IntValue ASC Bar.StringValue DESC)");
/// var results3 = realm.All<Foo>("Bar.IntValue > 0 SORT(Bar.IntValue ASC Bar.StringValue DESC) DISTINCT(Bar.IntValue)");
/// var results4 = realm.All<Foo>("Bar.IntValue > $0 || (Bar.String == $1 && Bar.Bool == $2)", 5, "small", true);
/// </code>
/// </example>
/// <seealso href="https://github.com/realm/realm-js/blob/master/docs/tutorials/query-language.md">
/// Examples of the NSPredicate syntax
/// </seealso>
/// <seealso href="https://academy.realm.io/posts/nspredicate-cheatsheet/">NSPredicate Cheatsheet</seealso>
public static IQueryable<T> Filter<T>(this IQueryable<T> query, string predicate, params RealmValue[] arguments)
{
Argument.NotNull(arguments, nameof(arguments));
var realmResults = Argument.EnsureType<RealmResults<T>>(query, $"{nameof(query)} must be a query obtained by calling Realm.All.", nameof(query));
return realmResults.GetFilteredResults(predicate, arguments);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "Validation happens in the core method.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "This is only used by the weaver and should not be exposed to users.")]
public static void PopulateCollection<T>(ICollection<T> source, ICollection<T> target, bool update, bool skipDefaults)
=> PopulateCollectionCore(source, target, update, skipDefaults, value => value);
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "Validation happens in the core method.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "This is only used by the weaver and should not be exposed to users.")]
public static void PopulateCollection<T>(IDictionary<string, T> source, IDictionary<string, T> target, bool update, bool skipDefaults)
=> PopulateCollectionCore(source, target, update, skipDefaults, kvp => kvp.Value);
private static void PopulateCollectionCore<T>(ICollection<T> source, ICollection<T> target, bool update, bool skipDefaults, Func<T, object> valueGetter)
{
Argument.NotNull(target, nameof(target));
if (!skipDefaults || source != null)
{
target.Clear();
}
var realm = ((IRealmCollection<T>)target).Realm;
if (source != null)
{
foreach (var item in source)
{
var value = valueGetter(item);
if (value is RealmObject obj && obj != null)
{
realm.Add(obj, update);
}
else if (value is RealmValue val && val.Type == RealmValueType.Object)
{
var wrappedObj = val.AsRealmObject();
if (wrappedObj is RealmObject robj)
{
realm.Add(robj, update);
}
}
target.Add(item);
}
}
}
}
}