Ejemplo n.º 1
0
        private void skinsChanged(IRealmCollection <SkinInfo> sender, ChangeSet changes, Exception error)
        {
            // This can only mean that realm is recycling, else we would see the protected skins.
            // Because we are using `Live<>` in this class, we don't need to worry about this scenario too much.
            if (!sender.Any())
            {
                return;
            }

            int protectedCount = sender.Count(s => s.Protected);

            // For simplicity repopulate the full list.
            // In the future we should change this to properly handle ChangeSet events.
            dropdownItems.Clear();
            foreach (var skin in sender)
            {
                dropdownItems.Add(skin.ToLive(realm));
            }
            dropdownItems.Insert(protectedCount, random_skin_info);

            Schedule(() =>
            {
                skinDropdown.Items = dropdownItems;

                updateSelectedSkinFromConfig();
            });
        }
Ejemplo n.º 2
0
 public RealmObservableCollection(IRealmCollection <TRealmObject> realmCollection,
                                  Func <TRealmObject, TObject> converter) : base(realmCollection.Select(converter))
 {
     _realmCollection = realmCollection;
     _converter       = converter;
     realmCollection.CollectionChanged += ChangesHandler;
 }
Ejemplo n.º 3
0
 public GraphViewModel()
 {
     Today     = TodoService.GetTodayList();
     Yesterday = TodoService.GetYesterdayList();
     ThisWeek  = TodoService.GetThisWeekList();
     LastWeek  = TodoService.GetLastWeekList();
     LastMonth = TodoService.GetLastMonthList();
 }
Ejemplo n.º 4
0
        protected IRealmCollection <T> Freeze <T>(IRealmCollection <T> collection)
            where T : RealmObject
        {
            var result = collection.Freeze();

            CleanupOnTearDown(result.Realm);
            return(result);
        }
Ejemplo n.º 5
0
 public GraphViewModel()
 {
     _service  = new TodoService();
     Today     = _service.GetTodayList();
     Yesterday = _service.GetYesterdayList();
     ThisWeek  = _service.GetThisWeekList();
     LastWeek  = _service.GetLastWeekList();
     LastMonth = _service.GetLastMonthList();
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Register a callback to be invoked each time this <see cref="T:Realms.IRealmCollection`1" /> changes.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This adds osu! specific thread and managed state safety checks on top of <see cref="IRealmCollection{T}.SubscribeForNotifications"/>.
        /// </para>
        /// <para>
        /// The first callback will be invoked with the initial <see cref="T:Realms.IRealmCollection`1" /> after the asynchronous query completes,
        /// and then called again after each write transaction which changes either any of the objects in the collection, or
        /// which objects are in the collection. The <c>changes</c> parameter will
        /// be <c>null</c> the first time the callback is invoked with the initial results. For each call after that,
        /// it will contain information about which rows in the results were added, removed or modified.
        /// </para>
        /// <para>
        /// If a write transaction did not modify any objects in this <see cref="T:Realms.IRealmCollection`1" />, the callback is not invoked at all.
        /// If an error occurs the callback will be invoked with <c>null</c> for the <c>sender</c> parameter and a non-<c>null</c> <c>error</c>.
        /// Currently the only errors that can occur are when opening the <see cref="T:Realms.Realm" /> on the background worker thread.
        /// </para>
        /// <para>
        /// At the time when the block is called, the <see cref="T:Realms.IRealmCollection`1" /> object will be fully evaluated
        /// and up-to-date, and as long as you do not perform a write transaction on the same thread
        /// or explicitly call <see cref="M:Realms.Realm.Refresh" />, accessing it will never perform blocking work.
        /// </para>
        /// <para>
        /// Notifications are delivered via the standard event loop, and so can't be delivered while the event loop is blocked by other activity.
        /// When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
        /// This can include the notification with the initial collection.
        /// </para>
        /// </remarks>
        /// <param name="collection">The <see cref="IRealmCollection{T}"/> to observe for changes.</param>
        /// <param name="callback">The callback to be invoked with the updated <see cref="T:Realms.IRealmCollection`1" />.</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="M:System.IDisposable.Dispose" />.
        ///
        /// May be null in the case the provided collection is not managed.
        /// </returns>
        /// <seealso cref="M:Realms.CollectionExtensions.SubscribeForNotifications``1(System.Collections.Generic.IList{``0},Realms.NotificationCallbackDelegate{``0})" />
        /// <seealso cref="M:Realms.CollectionExtensions.SubscribeForNotifications``1(System.Linq.IQueryable{``0},Realms.NotificationCallbackDelegate{``0})" />
        public static IDisposable?QueryAsyncWithNotifications <T>(this IRealmCollection <T> collection, NotificationCallbackDelegate <T> callback)
            where T : RealmObjectBase
        {
            if (!RealmAccess.CurrentThreadSubscriptionsAllowed)
            {
                throw new InvalidOperationException($"Make sure to call {nameof(RealmAccess)}.{nameof(RealmAccess.RegisterForNotifications)}");
            }

            return(collection.SubscribeForNotifications(callback));
        }
 private void OnCollectionUpdated(IRealmCollection <Task> sender, ChangeSet changes, Exception error)
 {
     //very naive implementation :)
     //OK for demo purposes
     Tasks.Clear();
     foreach (var item in sender)
     {
         Tasks.Add(new TaskViewModel(item));
     }
 }
Ejemplo n.º 8
0
        public static IDisposable?QueryAsyncWithNotifications <T>(this IRealmCollection <T> collection, NotificationCallbackDelegate <T> callback)
            where T : RealmObjectBase
        {
            // Subscriptions can only work on the main thread.
            if (!ThreadSafety.IsUpdateThread)
            {
                throw new InvalidOperationException("Cannot subscribe for realm notifications from a non-update thread.");
            }

            return(collection.SubscribeForNotifications(callback));
        }
Ejemplo n.º 9
0
        private void beatmapsChanged(IRealmCollection <BeatmapSetInfo> items, ChangeSet changes, Exception ___)
        {
            if (changes?.InsertedIndices == null)
            {
                return;
            }

            foreach (int c in changes.InsertedIndices)
            {
                beatmapUpdated(items[c]);
            }
        }
Ejemplo n.º 10
0
        internal virtual void ObjectChanged(IRealmCollection <RealmObject> sender, ChangeSet changes, Exception error) //internal for Tests
        {
            if (changes == null)
            {
                return;
            }
            if (_skipObjectChanges)
            {
                return;
            }

            lock (_objectChangedLock)
            {
                try
                {
                    using (var realmius = CreateRealmius())
                    {
                        using (var realm = _realmFactoryMethod())
                        {
                            realmius.Refresh();
                            foreach (var changesInsertedIndex in changes.InsertedIndices)
                            {
                                var obj = (IRealmiusObjectClient)sender[changesInsertedIndex];

                                HandleObjectChanged(obj, realmius, realm);
                            }

                            foreach (var changesModifiedIndex in changes.ModifiedIndices)
                            {
                                var obj = (IRealmiusObjectClient)sender[changesModifiedIndex];

                                HandleObjectChanged(obj, realmius, realm);
                            }

                            //delete can not be handled that way

                            /*
                             * foreach (var changesDeletedIndex in changes.DeletedIndices)
                             * {
                             *  var obj = (IRealmiusObjectClient)sender[changesDeletedIndex];
                             *
                             *  HandleObjectChanged(obj, realmius, realm, isDeleted: true);
                             * }*/
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Exception(e);
                    throw;
                }
            }
        }
Ejemplo n.º 11
0
        private void OnChange(IRealmCollection <T> sender, ChangeSet change, Exception error)
        {
            if (error != null)
            {
                Realm.NotifyError(error);
            }
            else if (!sender.IsValid)
            {
                RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            }
            else if (change != null)
            {
                if (change.Moves.Length > 0 &&
                    change.Moves.Length == change.InsertedIndices.Length &&
                    change.Moves.Length == change.DeletedIndices.Length)
                {
                    var ordered           = change.Moves.OrderBy(m => m.From);
                    var movedPositions    = -1;
                    var isConsecutiveMove = true;
                    foreach (var item in ordered)
                    {
                        if (movedPositions == -1)
                        {
                            movedPositions = item.To - item.From;
                        }
                        else if (item.To - item.From != movedPositions)
                        {
                            isConsecutiveMove = false;
                            break;
                        }
                    }

                    if (isConsecutiveMove)
                    {
                        var initialItem = ordered.First();
                        var movedItems  = Enumerable.Range(initialItem.To, change.Moves.Length)
                                          .Select(i => sender[i])
                                          .ToList();

                        RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, movedItems, initialItem.To, initialItem.From));
                    }
                    else
                    {
                        RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                    }

                    RaisePropertyChanged();
                    return;
                }

                var raiseRemoved = TryGetConsecutive(change.DeletedIndices, _ => default, out var removedItems, out var removedStartIndex);
        void UpdateTodos(IRealmCollection <TodoItem> sender, ChangeSet changes, Exception error)
        {
            if (error != null)
            {
                return;
            }

            if (changes == null)
            {
                var todos = sender.Select(ToModel).ToList();

                Todos = new ObservableCollection <TodoModel>(todos);

                return;
            }

            for (int i = 0; i < changes.DeletedIndices?.Length; i++)
            {
                Todos.RemoveAt(changes.DeletedIndices[i]);
            }

            for (int i = 0; i < changes.InsertedIndices?.Length; i++)
            {
                var item = sender[changes.InsertedIndices[i]];
                Todos.Insert(changes.InsertedIndices[i], ToModel(item));
            }

            for (int i = 0; i < changes.ModifiedIndices?.Length; i++)
            {
                var item  = sender[changes.ModifiedIndices[i]];
                var model = Todos[changes.ModifiedIndices[i]];

                model.Title       = item.Title;
                model.Deadline    = item.Deadline;
                model.Done        = item.Done;
                model.HasDeadline = item.Deadline.HasValue;
            }

            for (int i = 0; i < changes.Moves?.Length; i++)
            {
                var move = changes.Moves[i];
                var temp = Todos[move.From];

                Todos[move.From] = Todos[move.To];
                Todos[move.To]   = temp;
            }
        }
Ejemplo n.º 13
0
        private void beatmapsChanged(IRealmCollection <BeatmapSetInfo> sender, ChangeSet?changes, Exception error)
        {
            currentlyLoadedBeatmaps.Text = FirstRunSetupBeatmapScreenStrings.CurrentlyLoadedBeatmaps(sender.Count);

            if (sender.Count == 0)
            {
                currentlyLoadedBeatmaps.FadeColour(colours.Red1, 500, Easing.OutQuint);
            }
            else if (changes != null && (changes.DeletedIndices.Any() || changes.InsertedIndices.Any()))
            {
                currentlyLoadedBeatmaps.FadeColour(colours.Yellow)
                .FadeColour(OverlayColourProvider.Content2, 1500, Easing.OutQuint);

                currentlyLoadedBeatmaps.ScaleTo(1.1f)
                .ScaleTo(1, 1500, Easing.OutQuint);
            }
        }
Ejemplo n.º 14
0
        private void beatmapsChanged(IRealmCollection <BeatmapSetInfo> sender, ChangeSet changes, Exception error)
        {
            if (changes == null)
            {
                beatmapSets.Clear();
                // must use AddRange to avoid RearrangeableList sort overhead per add op.
                beatmapSets.AddRange(sender.Select(b => b.ToLive(realm)));
                return;
            }

            foreach (int i in changes.InsertedIndices)
            {
                beatmapSets.Insert(i, sender[i].ToLive(realm));
            }

            foreach (int i in changes.DeletedIndices.OrderByDescending(i => i))
            {
                beatmapSets.RemoveAt(i);
            }
        }
Ejemplo n.º 15
0
        private void OnChange(IRealmCollection <T> sender, ChangeSet change, Exception error)
        {
            if (error != null)
            {
                Realm.NotifyError(error);
            }
            else if (change != null)
            {
                IList removedItems;
                int   removedStartIndex;
                var   raiseRemoved = TryGetConsecutive(change.DeletedIndices, _ => default(T), out removedItems, out removedStartIndex);

                IList addedItems;
                int   addedStartIndex;
                var   raiseAdded = TryGetConsecutive(change.InsertedIndices, i => this[i], out addedItems, out addedStartIndex);

                if (raiseAdded || raiseRemoved)
                {
                    if ((raiseAdded && raiseRemoved) ||
                        (raiseAdded && addedItems == null) ||
                        (raiseRemoved && removedItems == null))
                    {
                        RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                        return;
                    }

                    if (removedItems != null)
                    {
                        RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, removedStartIndex));
                    }

                    if (addedItems != null)
                    {
                        RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, addedItems, addedStartIndex));
                    }
                }
            }
        }
        private static void HandleNotificationCallbackDelegate <T>(ObservableCollection <T> messages, IQueryable <T> results, IRealmCollection <T> realmMessages, ChangeSet changes, Exception error) where T : RealmObject
        {
            var isFirstResponse = changes == null;

            if (isFirstResponse)
            {
                realmMessages.ForEach(messages.Add);
            }
            else
            {
                changes?.InsertedIndices.ForEach(i => messages.Insert(i, realmMessages[i]));
                changes?.ModifiedIndices.ForEach(i => messages[i] = realmMessages[i]);
            }
        }
Ejemplo n.º 17
0
 protected ObservableGroupedCollection(IRealmCollection <TKey> collection, Func <TKey, TValue> converter)
 {
     _collection = collection;
     _converter  = converter;
 }
Ejemplo n.º 18
0
 public void GetCats()
 {
     _cats = _catService.GetCats();
 }
 public GroupedCollection(IRealmCollection<TKey> objects, Func<TKey, IRealmCollection<TValue>> valueSelector)
     : base(objects, o => new ObservableGrouping<TKey, TValue>(o, valueSelector))
 {
 }
Ejemplo n.º 20
0
 private void UploadRequestItemChanged(IRealmCollection <RealmObject> sender, ChangeSet changes, Exception error)
 {
     StartUploadTask();
 }
Ejemplo n.º 21
0
 private void UploadFileChanged(IRealmCollection <UploadFileInfo> sender, ChangeSet changes, Exception error)
 {
     UploadFiles();
 }
Ejemplo n.º 22
0
 private void skinChanged(IRealmCollection <T> sender, ChangeSet changes, Exception error) => invalidateCache();
Ejemplo n.º 23
0
 internal static IGroupedCollection <TKey, TValue> ToGroupedCollection <TKey, TValue>(this IRealmCollection <TKey> collection, Func <TKey, IRealmCollection <TValue> > valueSelector)
     where TKey : RealmObject
     where TValue : RealmObject
 {
     return(new GroupedCollection <TKey, TValue>(collection, valueSelector));
 }
Ejemplo n.º 24
0
    public BackLinkApp()
    {
        realm             = Realm.GetInstance("backlinks.realm");
        allMessageThreads = (IRealmCollection <MessageThread>)realm.All <MessageThread>();
        var messageCell = new DataTemplate(typeof(TextCell));

        messageCell.SetBinding(TextCell.TextProperty, "Body");
        messageCell.SetBinding(TextCell.DetailProperty, "Guid");
        var messageListView = new ListView
        {
            ItemTemplate = messageCell,
        };
        var threadCell = new DataTemplate(typeof(TextCell));

        threadCell.SetBinding(TextCell.TextProperty, "Guid");
        var messageThreadListView = new ListView
        {
            ItemsSource  = allMessageThreads,
            ItemTemplate = threadCell
        };

        messageThreadListView.ItemSelected += (sender, e) =>
        {
            currentMessageThreadPriKey   = (messageThreadListView.SelectedItem as MessageThread).Guid;
            currentMessageThread         = (IRealmCollection <MessageThread>)realm.All <MessageThread>().Where((messageThread) => messageThread.Guid == currentMessageThreadPriKey);
            messageListView.ItemsSource  = currentMessageThread?.FirstOrDefault()?.Messages;
            addMessageToThread.IsEnabled = currentMessageThread?.Count() > 0;
        };
        addMessageThread = new Button {
            Text = "Add New MessageThread"
        };
        addMessageThread.Clicked += (sender, e) =>
        {
            realm.Write(() =>
            {
                var messageThread = new MessageThread {
                    Guid = Guid.NewGuid().ToString()
                };
                realm.Add(messageThread);
            });
        };
        addMessageToThread = new Button {
            Text = "Add New Message to Thread", IsEnabled = false
        };
        addMessageToThread.Clicked += (sender, e) =>
        {
            realm.Write(() =>
            {
                currentMessageThread = (IRealmCollection <MessageThread>)realm.All <MessageThread>().Where((messageThread) => messageThread.Guid == currentMessageThreadPriKey);
                var counter          = currentMessageThread.FirstOrDefault().Messages.Count() + 1;
                var message          = new Message {
                    Guid = Guid.NewGuid().ToString(), Body = $"StackoverFlow:{counter}"
                };
                currentMessageThread?.FirstOrDefault()?.Messages.Add(message);
            });
        };
        MainPage = new ContentPage
        {
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children        =
                {
                    addMessageThread, messageThreadListView, addMessageToThread, messageListView
                }
            }
        };
    }