public async Task <IEnumerable <StoryDTO> > GetTopStoriesAsync() { var key = GetTopStoriesCacheKey(); if (cacheService.Get(key) is IReadOnlyCollection <StoryDTO> stories) { return(stories); } var topStoriesIds = await hackerNewsClient.GetTopStoriesAsync(topStoriesSize); if (topStoriesIds == null || topStoriesIds.Count == 0) { return(Enumerable.Empty <StoryDTO>()); } stories = (await Task.WhenAll(topStoriesIds.Select(o => hackerNewsClient.GetStoryAsync(o)))).ToDto(); if (stories.Count > 0) { cacheService.Add(key, stories, cacheTimeInMinutes); } return(stories); }
public async void RefreshTopStories() { if (!isUpdating.GetAndSet(true)) { NotifyOfPropertyChange("IsUpdating"); try { var newStories = await hn.GetTopStoriesAsync(); var existingIds = new HashSet <long>(topStories.Select(ts => ts.Id)); var added = false; // assuming that story IDs are chronologically-ordered foreach (var story in from ns in newStories where !existingIds.Contains(ns.Id) orderby ns.Id ascending select new TopStoryViewModel(ns, navigationService)) { added = true; topStories.Insert(0, story); } if (added && existingIds.Count > 0) { // need to sort the list var items = topStories.OrderBy(ts => ts.Id).ToList(); topStories.Clear(); foreach (var ts in items) { topStories.Add(ts); } } } catch (Exception ex) { // whoops Log.Error(ex); } finally { IsUpdating = false; } } }