Inventory
Inventory copied to clipboard
Integrate Pub / Sub system for view models communication
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);
}
}