1

I'm trying to get TopStories from hackernews API into a ListView. I want infinite scrolling so I'm using ISupportIncrementalLoading interface. Below is the code in LoadMoreItemsAsync method.

var httpClient = new HttpClient();
var response = await httpClient.GetAsync(new Uri("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"));
var json = await response.Content.ReadAsStringAsync();
List<string> topStoriesID = JsonConvert.DeserializeObject<List<string>>(json);
ObservableCollection<RootObject> ro = new ObservableCollection<RootObject>();

do
{
    var firstFewItems = (from topItemsID in topStoriesID
                         select topItemsID).Skip(lastItem).Take((int)count);
    foreach (var element in firstFewItems)
    {
        var itemResponse = await httpClient.GetAsync(new Uri("https://hacker-news.firebaseio.com/v0/item/" + element + ".json?print=pretty"));
        itemJson = await itemResponse.Content.ReadAsStringAsync();
        ro.Add(JsonConvert.DeserializeObject<RootObject>(itemJson));
        lastItem = (int)count;
        count = count + count;
    }
                    
 } while (lastItem != 500);

await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () =>
    {
        foreach (var item in ro)
        {
            this.Add(item);
        }
     });
return new LoadMoreItemsResult() { Count = count };

Running the code gives me a blank page with no errors. The URL returns 500 items so what I'm doing here is that first I'm storing 500 items IDs in topStoriesID list.

Then I'm taking first few items ID by using Skip().Take() methods and then running a foreach loop on this IDs for fetching actual stories and adding them in ObservableCollection object ro. I keep doing this until lastItem reaches to 500.

Is this code correct or is there a better way to implement it?

Zoe
  • 27,060
  • 21
  • 118
  • 148
monik
  • 11
  • 1
  • If you are loading all the items anyway, then a small hint: ListView prodides data virtualization. You do not need to care about this, as it only loads the currently viewed items (plus some buffer above and below). Even worth: Adding items step by step causes a lot of redraws. – Kai Brummund Jul 23 '15 at 08:12
  • There are some strange parts too: What is your **count** variable and why are you always casting it to *int*. The line count = count + count doubles your count every time. Didn't you mean count++ (count = count + 1)? – Kai Brummund Jul 23 '15 at 08:17
  • The thing is that first URL returns an array of 500 strings. Now these strings are actually IDs of items from TopStories. Then I load actual items by appending those IDs in second URL and adding it in a collection. Now all these would take too much time. So I want a small amount, say 15, items to load and when user reaches to bottom/end of screen, next 15 items should load. – monik Jul 23 '15 at 08:46

0 Answers0