简体   繁体   中英

Async ObservableCollection from Interface in C# (Xamarin)

I've got an ObservableCollection in an interface and I'm using it with a RestApi-Request . It has some Await functions and it must be async. But there's an error.

Here's the interface:

public interface IDbConnection
{
    ObservableCollection<Einkauf> GetEinkauf();
}

Here's the part from the class it is using:

public partial class RestView : IDbConnection
{
    private ObservableCollection<Einkauf> _einkauf;
    private const string Url = "http://localhost:3003/einkauf";
    private HttpClient _client = new HttpClient();

    public RestView ()
    {
        InitializeComponent ();
    }

    public async ObservableCollection<Einkauf> GetEinkauf()
    {
        var content = await _client.GetStringAsync(Url);
        var einkauf = JsonConvert.DeserializeObject<List<Einkauf>>(content);
        _einkauf = new ObservableCollection<Einkauf>(einkauf);
        speisenListe.ItemsSource = _einkauf;
        return _einkauf;
    }

}

The GetEinkauf is underlined and it says:

CS1983 C# The return type of an async method must be void, Task or Task<T>

Does anybody know how to fix this?

public interface IDbConnection
{
    Task<ObservableCollection<Einkauf>> GetEinkauf();
}

public async Task<ObservableCollection<Einkauf>> GetEinkauf()
{
  ...
}

If GetEinkauf is supposed to be implemented as an asynchronous method, you should change it return type to Task<ObservableCollection<Einkauf>> and also change its name to GetEinkauf Async to follow the naming convention for asynchronous methods:

public interface IDbConnection
{
    Task<ObservableCollection<Einkauf>> GetEinkaufAsync();
}

public async Task<ObservableCollection<Einkauf>> GetEinkaufAsync()
{
    var content = await _client.GetStringAsync(Url);
    var einkauf = JsonConvert.DeserializeObject<List<Einkauf>>(content);
    _einkauf = new ObservableCollection<Einkauf>(einkauf);
    speisenListe.ItemsSource = _einkauf;
    return _einkauf;
}

You could then await the method from any method marked as async :

var collection = await GetEinkaufAsync();

If another class implements the IDbConnection interface in a synchronous fashion for some reason, it could use the Task.FromResult method to return a Task<ObservableCollection<Einkauf>> :

public class SomeOtherClass : IDbConnection
{
    public Task<ObservableCollection<Einkauf>> GetEinkaufAsync()
    {
        return Task.FromResult(new ObservableCollection<Einkauf>());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM