public async Task <int> Unsubscribe(int userId, string topic, SubscribeItem.SubType type) { using (var context = new HypixelContext()) { var subs = context.SubscribeItem.Where(s => s.UserId == userId && s.TopicId == topic && s.Type == type).FirstOrDefault(); if (subs != null) { context.SubscribeItem.Remove(subs); } if (type.HasFlag(SubscribeItem.SubType.PRICE_HIGHER_THAN) || type.HasFlag(SubscribeItem.SubType.PRICE_LOWER_THAN)) { RemoveSubscriptionFromCache(userId, topic, type, PriceUpdate); } if (type.HasFlag(SubscribeItem.SubType.SOLD)) { RemoveSubscriptionFromCache(userId, topic, type, Sold); } if (type.HasFlag(SubscribeItem.SubType.OUTBID)) { RemoveSubscriptionFromCache(userId, topic, type, outbid); } if (type.HasFlag(SubscribeItem.SubType.AUCTION)) { RemoveSubscriptionFromCache(userId, topic, type, AuctionSub); } return(await context.SaveChangesAsync()); } }
private static void RemoveSubscriptionFromCache(int userId, string topic, SubscribeItem.SubType type, ConcurrentDictionary <string, ConcurrentBag <SubscribeItem> > target) { if (target.Remove(topic, out ConcurrentBag <SubscribeItem> value)) { target.AddOrUpdate(topic, (key) => RemoveOldElement(userId, topic, type, value), (key, old) => RemoveOldElement(userId, topic, type, old)); } }
private static bool SubscribeItemEqual(int userId, string topic, SubscribeItem.SubType type, SubscribeItem s) { return(s.UserId == userId && s.TopicId == topic && s.Type == type); }
private static ConcurrentBag <SubscribeItem> RemoveOldElement(int userId, string topic, SubscribeItem.SubType type, ConcurrentBag <SubscribeItem> old) { return(new ConcurrentBag <SubscribeItem>(old.Where(s => !SubscribeItemEqual(userId, topic, type, s)))); }