Skip to content

Integrate Pub / Sub system for view models communication #28

Description

@LeftTwixWand

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);
    }
}

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestfeature requestMeans some additional functionality is askedlayer/applicationMeans some changes in the Application layerlayer/infrastructureMeans some changes in the Infrastructure layer

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions