LeftTwixWand / Inventory

New version of Microsoft Inventory sample, built on WinUI 3, using DDD and Clean Architecture approach
MIT License
71 stars 10 forks source link

Integrate Pub / Sub system for view models communication #28

Open LeftTwixWand opened 1 year ago

LeftTwixWand commented 1 year ago

CommunityToolkit.Mvvm.Messaging provides IMessenger interface, that allows us to set up Pub / Sub system for flexible ViewModels communication.

How it can be useful? We have a ProductsView with ProductsViewModel, which has a list of products. And a ProductView with ProductViewModel, where we can see some detail information, modify it, delete current product or to add a new one.

After we added, edited or deleted a product - we can just send a message, what we've modified. And the main ProductsViewModel will handle it and will update its collection. So, we won't need to load all the products from the database after every modification - we just will need to update im-memoty Observable collection.

// Define a message
public sealed class ProductDeletedMessage : ValueChangedMessage<int>
{
    public ProductDeletedMessage(int productId) : base(productId)
    {
    }
}
// Send a message
public sealed partial class ProductViewModel : ObservableObject
{
    [RelayCommand]
    private void DeleteItem(int productId)
    {
        WeakReferenceMessenger.Default.Send(new ProductDeletedMessage(productId));
    }
}
// Handle a message
public sealed partial class ProductsViewModel : ObservableRecipient, IRecipient<ProductDeletedMessage>
{
    public ProductsViewModel()
    {
        // Activate message listener
        IsActive = true;
    }

    public ObservableCollection<ProductModel> Products { get; } = new();

    public void Receive(ProductDeletedMessagemessage)
    {
        var productToDelete = Products.First(prodcut => prodcut.Id == message.Value);
        Products.Remove(productToDelete);
    }
}