-2

I have following method which will eventually return some Task<IList<DataModel>> but for now just returns null. I want to load result of this list to ObservableCollection in my ViewModel which is then displayed in a ListView.

But for now, I just want to return null and check that that is handled properly, so my ListView should show nothing in it as a result. I simmulate that by this code:

public async Task<IList<DatatModel>> GetData(string id)
{
    return await Task.FromResult<IList<DataModel>>(null);
}

I call the code above and will loop through result of my Task and load it all in my ObservableCollection like so:

public void Initialize()
{
    foreach (var data in GetData(Id).Result)
    {
        MyObservableCollection.Add(data);
    }
}

However, my app just freezes. I think that above call to GetData(id).Result is problem because Result is null. How do I loop through this data and load it into my ObservableCollection if some data exist, or simply dont load anything if there is no data returned?

pixel
  • 9,653
  • 16
  • 82
  • 149
  • what do you mean by freeze? If you call foreach on a null object, I believe that will throw an exception – weijia_yu Jan 22 '19 at 21:50
  • "However, my app just freezes" Nope, it doesn't. Or, if your code is actually this, it wouldn't. It'd throw a NRE. What's happening here is unclear. Have you debugged it? Is other code catching and doing something else? Throw your example into a console application and see what happens. –  Jan 22 '19 at 21:51
  • @Will yes it is NRE, you are right. So, how to check for null on an Result to not use it if it is null? – pixel Jan 22 '19 at 21:54
  • 1
    Lots of ways. First thing you need to do is stop using .Result on a task. If you must access a Task without using the async/await pattern, use .ContinueWith. Next, check the result and don't iterate over it if it's null. –  Jan 22 '19 at 21:59

1 Answers1

2

Instead of returning null, return an empty List<DataModel>. That way, your Result property will always be populated. So, your GetData method would become:

public async Task<IList<DatatModel>> GetData(string id)
{
    return await Task.FromResult<IList<DataModel>>(new List<DataModel>());
}
Wayne Allen
  • 1,605
  • 1
  • 10
  • 16
  • 1
    The point of the question is how to properly handle a null result. Avoiding a null result doesn't really answer the question. –  Jan 22 '19 at 21:55
  • Also, you could remove the async/await from the function, both are redundant in this case. – Evan Trimboli Jan 22 '19 at 21:58