Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 42 ยท MVVM and Navigation

Loading State, Errors and Async View Models

Build robust asynchronous view models in .NET MAUI: IsBusy and view states, loading on appearing, error handling, retry, CancellationToken, the UI thread, and a runnable async view-model stand-in.

Real screens wait for things: a web request, a database read, a file. While they wait, the user must see that something is happening, and when something fails, the user must see what to do next. A view model that handles loading, success, empty and error states cleanly is the difference between an app that feels solid and one that feels broken. This lesson builds that pattern step by step.

MAUI pages cannot run on this site, so the XAML is read-only. The async view models are plain C# and run on Piston; a small console loop plays the part of the screen and is labelled as a stand-in.

Model the screen as a state

A common beginner design is a handful of unrelated booleans (IsLoading, HasError, IsEmpty...) that can contradict each other: loading and error at the same time. A single state value cannot:

C#
public enum ViewState { Idle, Loading, Content, Empty, Error }

The view model exposes State, derived booleans for the XAML, and the data:

C#
public partial class ProductsViewModel(IProductService service) : ObservableObject
{
    [ObservableProperty, NotifyPropertyChangedFor(nameof(IsLoading), nameof(IsContent), nameof(IsEmpty), nameof(IsError))]
    private ViewState state = ViewState.Idle;

    [ObservableProperty] private string errorMessage = "";

    public ObservableCollection<Product> Items { get; } = new();

    public bool IsLoading => State == ViewState.Loading;
    public bool IsContent => State == ViewState.Content;
    public bool IsEmpty => State == ViewState.Empty;
    public bool IsError => State == ViewState.Error;
}

And the page shows exactly one block per state:

XML
<Grid>
    <ActivityIndicator IsRunning="{Binding IsLoading}" IsVisible="{Binding IsLoading}"
                       HorizontalOptions="Center" VerticalOptions="Center" />

    <CollectionView ItemsSource="{Binding Items}" IsVisible="{Binding IsContent}" />

    <Label Text="No products yet." IsVisible="{Binding IsEmpty}"
           HorizontalOptions="Center" VerticalOptions="Center" />

    <VerticalStackLayout IsVisible="{Binding IsError}" VerticalOptions="Center" Spacing="12">
        <Label Text="{Binding ErrorMessage}" HorizontalTextAlignment="Center" />
        <Button Text="Try again" Command="{Binding LoadCommand}" />
    </VerticalStackLayout>
</Grid>

Always give failures a way out: a retry button, a hint to check the connection, or a link to settings.

The loading method

C#
[RelayCommand]
private async Task LoadAsync(CancellationToken token)
{
    State = ViewState.Loading;
    try
    {
        var products = await service.GetProductsAsync(token);

        Items.Clear();
        foreach (var p in products) Items.Add(p);

        State = Items.Count == 0 ? ViewState.Empty : ViewState.Content;
    }
    catch (OperationCanceledException)
    {
        // the user left the page: stay quiet
    }
    catch (HttpRequestException)
    {
        ErrorMessage = "Could not reach the server. Check your connection.";
        State = ViewState.Error;
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "Loading products failed");
        ErrorMessage = "Something went wrong. Please try again.";
        State = ViewState.Error;
    }
}

Four details deserve attention:

  1. Set the state first so the spinner shows before the first await.
  2. Catch specific exceptions you can explain to the user (no network, timeout, 404) and one generic fallback that also logs the full exception for you. Users get a friendly message; you get the stack trace.
  3. Cancellation is normal, not an error. Do not show an error dialog when the user simply navigated away.
  4. A stale response must not overwrite a fresh one (see below).
C# Stand-in: states, errors and retry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When to load: OnAppearing, not the constructor

A constructor cannot be async, and fire-and-forget calls there hide errors. Typical places to start loading:

  • OnAppearing of the page, which calls await viewModel.LoadCommand.ExecuteAsync(null) (or a InitializeAsync method). Guard it so it does not reload each time the user returns, if the data is still fresh.
  • The Loaded event or the Community Toolkit's EventToCommandBehavior for Appearing.
  • A RefreshView command for pull-to-refresh (see CollectionView and Lists).
C#
protected override async void OnAppearing()
{
    base.OnAppearing();
    await viewModel.LoadCommand.ExecuteAsync(null);
}

OnAppearing is async void because it overrides a void method; keep the body small and let the command handle exceptions.

Cancellation

If the user leaves a screen while a request is in flight, cancel it. A CancellationTokenSource lives in the view model; the page cancels it in OnDisappearing:

C#
private CancellationTokenSource? cts;

public async Task LoadAsync()
{
    cts?.Cancel();                        // a new load replaces the old one
    cts = new CancellationTokenSource();
    var token = cts.Token;

    var data = await service.GetAsync(token);
    if (token.IsCancellationRequested) return;    // stale: ignore the result
    Apply(data);
}

public void Cancel() => cts?.Cancel();

This also solves search as you type: each keystroke cancels the previous request, so a slow answer for "ap" cannot overwrite the fast answer for "apple". With the toolkit, [RelayCommand(IncludeCancelCommand = true)] generates the cancel command for you.

C# Stand-in: cancel the previous request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The UI thread

Property changes and collection changes that update the screen must happen on the main (UI) thread. After an await in a view model that was started from the UI thread, execution normally returns to it (the synchronization context is captured), so most code just works. When work starts elsewhere, for example a timer, a sensor callback or Task.Run, marshal back:

C#
MainThread.BeginInvokeOnMainThread(() => Items.Add(newItem));
await MainThread.InvokeOnMainThreadAsync(() => Status = "Done");

Use Task.Run only for real CPU-bound work such as parsing a huge file; I/O-bound calls (HttpClient, database) are already asynchronous. Never block with .Result or .Wait() on the UI thread: it freezes the app or deadlocks.

Error messages that help

  • Say what happened and what the user can do: "No internet connection. Check Wi-Fi and try again."
  • Do not show raw exception text, URLs or stack traces to users.
  • Log the details (with a logger such as ILogger<T>, or a crash-reporting service) so you can fix them.
  • For temporary failures, retry automatically with a short delay (two or three attempts), then show the error state.
  • Keep stale data visible when a refresh fails ("Showing saved data, could not refresh") instead of clearing the list.

One state at a time

Loading Spinner, disable actions
Content The list or the details
Empty A friendly "nothing yet"
Error Message plus Try again

A single state value cannot contradict itself.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why model the screen with a single State value instead of several booleans?

    With separate flags, loading and error could both be true. One state value keeps exactly one condition at a time.
  2. 2. Where should an async load normally start?

    A constructor cannot await, and exceptions there are hard to handle; OnAppearing can call an async command.
  3. 3. How should you treat OperationCanceledException caused by leaving the page?

    Cancellation is a normal outcome when the user navigates away, so it should not look like a failure.
  4. 4. Why cancel the previous request in a search-as-you-type box?

    Responses can arrive out of order; cancelling or ignoring stale ones prevents showing results for old text.

Summary

  • Model a screen as Idle, Loading, Content, Empty or Error, and show one block per state.
  • Start loading in OnAppearing or a command, never in a constructor; set Loading before the first await.
  • Catch specific failures, show friendly text with a retry, and log details.
  • Use CancellationToken to cancel leaving-the-page and stale requests.
  • Touch UI-bound data on the main thread, and never block it with .Result.

Next: Platform-Specific Code