I am writing a Blazor application that is composed of several components; for example, the UserExplorer component provides functionality to view, add, update, and remove users.
Each of these functions exists as its own component; for example:
AddUseris a form that creates a new user.ViewUsersis a table that displays all users.
I believe that this is good practice for components as it keeps them clean and aligns with the Single Responsibility Principle, but it incurs some problems, specifically to do with state changes across components; for example, calling StateHasChanged from the AddUsers component does not update the table in the ViewUsers component.
+-----------------+ | UserExplorer |+-----------------+ /\ / \ / \ / \ +-------------++-------------+| AddUser |-?>| ViewUsers |+-------------++-------------+Note: -?> denotes that I want changes in AddUser to propagate to ViewUsers.
If I were using a JavaScript SPA framework, like Angular, I might use something like RxJS or NgRx to solve this problem, so what I'm wondering is, does the same approach apply in Blazor, or is there something I'm missing?
Here's what I've tried so far...the following class is a simple event bus that I can publish from, and subscribe to.
For brevity, I have only included the interface here. The implementation details are superfluous, as I'm trying to identify whether conceptually, an event bus is the right approach.
public interface IEventBus { void Subscribe(string eventName, Action action); void Subscribe(string eventName, Func<Task> action); void Unsubscribe(string eventName, Action action); void Unsubscribe(string eventName, Func<Task> asyncAction); Task PublishAsync(string eventName);}Assuming that IEventBus is wired up as an injectable dependency...
services.AddSingleton<IEventBus, EventBus>();...I can now call this from each component.
Publish from AddUser:
await eventBus.PublishAsync("user added");Subscribe from ViewUsers:
eventBus.Subscribe("user added", async () => await LoadUsers());Whilst this approach works and doesn't incur an enormous headache in trying to coordinate event propagation, what I want to know is:
- Is this a recommended, or even good approach in the first place?
- If the above is true, what should I be using, rather than rolling my own event bus?
- If the above is false, what am I missing?