ふるすたっくえんじにあの日記

ASP .NET MVC (C#)、.NET Framework、iOS (Objective-c) アプリ、Androidアプリ (Java)、AWSあたり

Prism PubSubEventを簡単に


GetEventとか長ったらしい。

おもむろに以下のクラスを実装しましょう。

using Prism.Events;
using System;

namespace Hoge
{
    public abstract class StaticPubSubEvent<T> : PubSubEvent where T : StaticPubSubEvent<T>, new()
    {
        private static EventAggregator eventAggregator = new EventAggregator();

        private static readonly T instance = eventAggregator.GetEvent<T>();

        protected StaticPubSubEvent() { }

        public static new void Publish() => eventAggregator.GetEvent<T>().InternalPublish();

        public static new SubscriptionToken Subscribe(Action action) => Subscribe(action, ThreadOption.PublisherThread);

        public static new SubscriptionToken Subscribe(Action action, ThreadOption threadOption) => Subscribe(action, threadOption, false);

        public static new SubscriptionToken Subscribe(Action action, bool keepSubscriberReferenceAlive) => Subscribe(action, ThreadOption.PublisherThread, keepSubscriberReferenceAlive);

        public static new SubscriptionToken Subscribe(Action action, ThreadOption threadOption, bool keepSubscriberReferenceAlive)
        {
            var actionReference = new DelegateReference(action, keepSubscriberReferenceAlive);

            EventSubscription subscription;
            switch (threadOption)
            {
                case ThreadOption.PublisherThread:
                    subscription = new EventSubscription(actionReference);
                    break;
                case ThreadOption.BackgroundThread:
                    subscription = new BackgroundEventSubscription(actionReference);
                    break;
                case ThreadOption.UIThread:
                    if (instance.SynchronizationContext == null) throw new InvalidOperationException();
                    subscription = new DispatcherEventSubscription(actionReference, instance.SynchronizationContext);
                    break;
                default:
                    subscription = new EventSubscription(actionReference);
                    break;
            }

            return eventAggregator.GetEvent<T>().InternalSubscribe(subscription);
        }
    }
}


で、イベントクラスを用意

namespace Hoge
{
    public sealed class HogeEvent : StaticPubSubEvent<HogeEvent> { }
}

Subscriber

HogeEvent.Subscribe(() =>
{
}, ThreadOption.UIThread);

Publisher

HogeEvent.Publish();

ぼくは気にしないけど、若干いまいちですね。何がいまいちかわかる人だけ自己責任で使ってくださいw(ヒント:EventAggregator