BlazorComponentBus icon indicating copy to clipboard operation
BlazorComponentBus copied to clipboard

API design issue

Open tinytownsoftware opened this issue 3 years ago • 1 comments
trafficstars

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.

tinytownsoftware avatar Aug 22 '22 10:08 tinytownsoftware

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

tinytownsoftware avatar Aug 22 '22 10:08 tinytownsoftware

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.

cjbush avatar Sep 28 '22 14:09 cjbush

Thanks CJ. The code base has been updated and a new package version has been deployed (v2.2.0)

cpear avatar Oct 12 '22 10:10 cpear

This is fantastic. I started playing with this library last night and was wondering if this was possible. 🎉

ryanbuening avatar Nov 03 '22 21:11 ryanbuening