Exemplo n.º 1
0
        /// <summary>
        /// Saves an item to the list.  If the item does not have an Id, then the item
        /// is considered new and will be added to the end of the list.  Otherwise, the
        /// item is considered existing and is replaced.
        /// </summary>
        /// <param name="item">The new item</param>
        /// <returns>A task that completes when the item is saved.</returns>
        public Task SaveItemAsync(TodoItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            item.Version   = Guid.NewGuid().ToString();
            item.UpdatedAt = DateTimeOffset.UtcNow;

            if (item.Id == null)
            {
                item.Id = Guid.NewGuid().ToString();
                _items.Add(item);
                TodoItemsUpdated?.Invoke(this, new TodoServiceEventArgs(TodoServiceEventArgs.ListAction.Add, item));
            }
            else
            {
                var itemToReplace = _items.SingleOrDefault(m => m.Id == item.Id);
                if (itemToReplace != null)
                {
                    var idx = _items.IndexOf(itemToReplace);
                    _items[idx] = item;
                    TodoItemsUpdated?.Invoke(this, new TodoServiceEventArgs(TodoServiceEventArgs.ListAction.Update, item));
                }
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Removes an item in the list, if it exists.
        /// </summary>
        /// <param name="item">The item to be removed</param>
        /// <returns>A task that completes when the item is removed.</returns>
        public Task RemoveItemAsync(TodoItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (item.Id != null)
            {
                var itemToRemove = _items.SingleOrDefault(m => m.Id == item.Id);
                if (itemToRemove != null)
                {
                    _items.Remove(itemToRemove);
                    TodoItemsUpdated?.Invoke(this, new TodoServiceEventArgs(TodoServiceEventArgs.ListAction.Delete, itemToRemove));
                }
            }

            return(Task.CompletedTask);
        }