-
Notifications
You must be signed in to change notification settings - Fork 0
/
NewsViewModel.cs
73 lines (64 loc) · 2.26 KB
/
NewsViewModel.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
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace HackerNews;
public class NewsViewModel(NewsService newsService, ILogger<NewsViewModel> logger) : ObservableObject
{
public ObservableCollection<StoryModel> TopStoryCollection { get; } = [];
private readonly NewsService _newsService = newsService;
private readonly ILogger<NewsViewModel> _logger = logger;
public async Task RefreshAsync()
{
// Ensure this method is called on the UI thread
await MainThread.InvokeOnMainThreadAsync(async () =>
{
try
{
TopStoryCollection.Clear();
var sortedStories = (await GetTopStoriesAsync().ToListAsync())
.OrderByDescending(story => story.Score)
.ToList();
foreach (var story in sortedStories)
{
TopStoryCollection.Add(story); // Add sorted stories to the collection
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while refreshing top stories.");
}
});
}
private async IAsyncEnumerable<StoryModel> GetTopStoriesAsync()
{
List<string> topStoryIds;
try
{
var topStoriesJson = await _newsService.GetTopStoryAsJsonAsync();
topStoryIds = JsonConvert.DeserializeObject<List<string>>(topStoriesJson);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while fetching top stories.");
yield break; // Stop if there’s an issue fetching the top story IDs
}
foreach (var id in topStoryIds)
{
StoryModel story;
try
{
story = await _newsService.GetTopStoryAsync(id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching story with ID: {StoryId}", id);
continue; // Skip this story if there's an error fetching it
}
if (story != null)
{
yield return story; // Yield only if successfully fetched
}
}
}
}