Skip to content

Instantly share code, notes, and snippets.

@conficient
Created September 13, 2019 15:05
Show Gist options
  • Save conficient/6c7393d9a37b492e8402da05362f4462 to your computer and use it in GitHub Desktop.
Save conficient/6c7393d9a37b492e8402da05362f4462 to your computer and use it in GitHub Desktop.
Blazor - State machines with events - example from FlightFinder
using FlightFinder.Shared;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace FlightFinder.Client.Services
{
public class AppState
{
// Actual state
public IReadOnlyList<Itinerary> SearchResults { get; private set; } // lists can only be updated via the State methods
public bool SearchInProgress { get; private set; }
private readonly List<Itinerary> shortlist = new List<Itinerary>();
public IReadOnlyList<Itinerary> Shortlist => shortlist;
// Lets components receive change notifications
// Could have whatever granularity you want (more events, hierarchy...)
public event Action OnChange; // event for changes
// Receive 'http' instance from DI
private readonly HttpClient http;
public AppState(HttpClient httpInstance)
{
http = httpInstance;
}
public async Task Search(SearchCriteria criteria)
{
SearchInProgress = true;
NotifyStateChanged();
SearchResults = await http.PostJsonAsync<Itinerary[]>("/api/flightsearch", criteria);
SearchInProgress = false;
NotifyStateChanged();
}
public void AddToShortlist(Itinerary itinerary)
{
shortlist.Add(itinerary);
NotifyStateChanged();
}
public void RemoveFromShortlist(Itinerary itinerary)
{
shortlist.Remove(itinerary);
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke(); // this method hides the OnChange to simplify it
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment