BlazorComponentBus
BlazorComponentBus copied to clipboard
API design issue
I've recently switched over to your library from using raw events, which were quite annoying and unscalable. One thing that would make it better as far as developer experience is illustrated by the following:
Bus.Subscribe<MyEvent>(args =>
{
var message = args.GetMessage<MyEvent>();
...
}
I really shouldn't have to do args.GetMessage<MyEvent>(). The variable args should be of type MyEvent. I have never used args for anything else other than getting the message I care about.
I wrote a quick set of extension args to help with this. Up to you if you want to incorporate them in a future version.
public static class BlazorComponentBusExtensions
{
public static void SubscribeTo<TMessage>(this IComponentBus bus, AsyncComponentCallBack<TMessage> callback)
{
bus.Subscribe<TMessage>(async (a, _) =>
{
var message = a.GetMessage<TMessage>();
await callback(message, _);
});
}
public static void SubscribeTo<TMessage>(this IComponentBus bus, ComponentCallBack<TMessage> callback)
{
bus.Subscribe<TMessage>((a) =>
{
var message = a.GetMessage<TMessage>();
callback(message);
});
}
}
I opened a PR to address this. Adding them as extension methods doesn't work in the general case because if you try to unsubscribe from the event, it's a different object reference for the callback since it's created internally to the extension method.
Thanks CJ. The code base has been updated and a new package version has been deployed (v2.2.0)
This is fantastic. I started playing with this library last night and was wondering if this was possible. 🎉