Publish an Event without PayLoad in Prism EventAggregator?

♀尐吖头ヾ 提交于 2019-12-04 02:22:09

Good question, I don't see a reason for not publishing an event without a payload. There are cases where the fact that an event has been raised is all information you need and want to handle.

There are two options: As it is open source, you can take the Prism source and extract a CompositePresentation event that doesn't take a payload.

I wouldn't do that, but handle Prism as a 3rd party library and leave it as it is. It is good practice to write a Facade for a 3rd party library to fit it into your project, in this case for CompositePresentationEvent. This could look something like this:

public class EmptyPresentationEvent : EventBase
{
    /// <summary>
    /// Event which facade is for
    /// </summary>
    private readonly CompositePresentationEvent<object> _innerEvent;

    /// <summary>
    /// Dictionary which maps parameterless actions to wrapped 
    /// actions which take the ignored parameter 
    /// </summary>
    private readonly Dictionary<Action, Action<object>> _subscriberActions;

    public EmptyPresentationEvent()
    {
        _innerEvent = new CompositePresentationEvent<object>();
        _subscriberActions = new Dictionary<Action, Action<object>>();
    }

    public void Publish()
    {
        _innerEvent.Publish(null);
    }

    public void Subscribe(Action action)
    {
        Action<object> wrappedAction = o => action();
        _subscriberActions.Add(action, wrappedAction);
        _innerEvent.Subscribe(wrappedAction);
    }

    public void Unsubscribe(Action action)
    {
        if (!_subscriberActions.ContainsKey(action)) return;
        var wrappedActionToUnsubscribe = _subscriberActions[action];
        _innerEvent.Unsubscribe(wrappedActionToUnsubscribe);
        _subscriberActions.Remove(action);
    }
}

If anything is unclear, please ask.

Just to update the situation since this question was asked/answered, as of Prism 6.2, empty payloads are now supported in Prism PubSubEvents.

If you're using an older version, this blog shows how to create an "Empty" class that clearly indicates the intent of the payload: https://blog.davidpadbury.com/2010/01/01/empty-type-parameters/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!