Nugget 16: Mediator Pattern in MVVM
Problem
As this little experiment of mine slowly turns into a tool I use every day, some design issues are starting to show. Nothing dramatic — just the usual growing pains. In this post, I want to talk about a data‑sharing issue between ViewModels and how the Mediator Pattern helped clean things up.
The symptom showed up in the Index view, where a grid lists all Job Applications. Earlier, I added date‑range filtering to that view. It works, but it also made the IndexViewModel a bit “fat.” It’s doing too many things now, and that’s something I’ll need to revisit.
When the user filters by date, the grid updates correctly. But then you go to the Home page, where the chart lives, and it still loads the entire dataset. It would make much more sense for the chart to reuse the same FromDate and ToDate and rebuild itself accordingly.
That’s where the Mediator Pattern comes in.
The Mediator Pattern
This pattern is common in MVVM. It lets sibling ViewModels communicate without knowing about each other. Instead, they both talk to a shared service — a mediator — and the mediator handles the rest.Why not just subscribe to IndexViewModel from HomeViewModel?
Technically, I could implement INotifyPropertyChanged in IndexViewModel and have HomeViewModel subscribe to it. But that’s a code smell:
- It creates a strong reference between the two ViewModels.
- It makes them tightly coupled.
- It hurts reusability.
- And INotifyPropertyChanged is meant for UI binding, not for ViewModel‑to‑ViewModel messaging
With the Mediator Pattern, both ViewModels depend only on a central service. They don’t even know the other exists. Much cleaner.
I like that.
Other Changes
While I was in there, I also pushed the date filtering down into SQL Server. EF Core makes that easy, and it avoids loading unnecessary data into memory.Wrapping Up
I’ll keep this Nugget short. You can check out the updated code directly in the GitHub repo. This little app is starting to walk on its own, and it’s earning its place in my toolbox as I keep pushing forward in my job search.Download the zip, clone it — who knows, it might help you too.
One reference for this Nugget is enough: The GitHub project
Comments
Post a Comment