Component Bus

Published on Saturday, December 30, 2023

Component Bus

Consider using the Blazor Component Bus for messaging instead of Fluxor. Fluxor is great for when you really need its functionality, but it requires you to write a fair amount of boilerplate, so consider lighter-weight options first. The Bus allows Blazor components to publish and subscribe to messages that you create.

Create a message with either no payload, or whatever payload you require:

public record SomethingHappenedMessage();
public record SomeDataMessage(string StringData, int IntData);

In the publishing component:

[Inject] private ComponentBus Bus { get; set; } = default!;

private async Task OnClick()
{
  await Bus.Publish(new SomeDataMessage("Hello", 5));
}

And in the subscribing component:

[Inject] private ComponentBus Bus { get; set; } = default!;

protected override void OnInitialized()
{
  base.OnInitialized();
  // Other code
  Bus.Subscribe<SomeDataMessage>(HandleSomeDataMessage);
}

private void HandleSomeDataMessage(MessageArgs args)
{
  InvokeAsync(() => // 
  {
  var message = args.GetMessage<SomeDataMessage>();
  // Do something with message.StringData and message.IntData
  StateHasChanged();
  });
}