CosmicPredator
CosmicPredator

Reputation: 109

A Constructor for Incremental Loading Collection Helpers in UWP C#

How can I add a constructor to my IncrementalLoadingCollection. I want to add a constructor to pass arguments to the GetPagedItemsAsync method to load data from an API.

My Incremental Loading Collection:

public class PeopleSource : IIncrementalSource<Person>
{
    private readonly List<Person> people;

    public PeopleSource(int maxValue)
    {
        // Creates an example collection.
        people = new List<Person>();

        for (int i = 1; i <= maxValue; i++)
        {
            var p = new Person { Name = "Person " + i };
            people.Add(p);
        }
    }

    public async Task<IEnumerable<Person>> GetPagedItemsAsync(int pageIndex, int pageSize)
    {
        // Gets items from the collection according to pageIndex and pageSize parameters.
        var result = (from p in people
                        select p).Skip(pageIndex * pageSize).Take(pageSize);

        // Simulates a longer request...
        await Task.Delay(1000);

        return result;
    }
}

The above code is an example from Microsoft. There is a constructor for People which takes an Argument named maxValue.

var collection = new IncrementalLoadingCollection<PeopleSource, Person>();

The above code is an Initialization of the Incremental Loading class. But where do I pass on the maxValue Argument?? Please Help me...

Upvotes: 1

Views: 80

Answers (1)

Mike Hofer
Mike Hofer

Reputation: 17002

What you're trying to do doesn't make much sense because functions/methods and constructors are fundamentally different things.

GetPagedItemsAsync is a function that returns a value (a Task<IEnumerable<Person>>). Constructors only ever return new instances of objects; in this case, a new instance of PeopleSource.

You cannot create a PeopleSource constructor that takes int maxSource and have it return a Task<IEnumerable<Person>>.

EDIT:

As an alternative, you could create a method that creates a new PeopleSource, then executes the GetPagedItemsAsync method.

public static Task<IEnumerable<Person>> GetPagedItemsAsync(int maxValue, int pageIndex, int pageSize)
{
    var instance = new PeopleSource(maxValue);
    return instance.GetPagedItemsAsync(pageIndex, pageSize);
}

Note that this is less than optimal, because if you have to invoke GetPagedItemsAsync multiple times, it will repopulate the PeopleSource instance every time you invoke it. This can be very expensive if the data comes from a database.

It's generally better to create the PeopleSource, store it in a variable, and then invoke GetPagedItemsAsync as many times as you need to off of the same instance.

Upvotes: 1

Related Questions