轻量级MVVM框架Stylet介绍:(8)事件聚合器

EventAggregator 是一个分散的、弱绑定的、基于发布/订阅的事件管理器。

发布者和订阅者

订阅者

对特定事件感兴趣的订阅者可以告诉 IEventAggregator 他们的兴趣,并且每当发布者将该特定事件发布到 IEventAggregator 时,都会收到通知。

事件是类 - 用它们做任何你想做的事情。例如:

class MyEvent { 
 
  // Do something 
 
}

订阅者必须实现IHandle,这是T就是希望接收到的事件的类型(当然也可以实现多个IHandle).然后必须获取一个IEventAggregator类型的实例,并且订阅自己,比如:

class Subscriber : IHandle<MyEvent>, IHandle<MyOtherEvent>
{
   public Subscriber(IEventAggregator eventAggregator)
   {
      eventAggregator.Subscribe(this);
   }
 
   public void Handle(MyEvent message)
   {
      // ...
   }
 
   public void Handle(MyOtherEvent message)
   {
      // ...
   }
}

发布者

发布者必须也能获取IEventAggregator的实例,但是不必订阅自己-只需要在每次发布事件时调用IEventAggregator.Publish即可。

class Publisher
{
   private IEventAggregator eventAggregator;
   public Publisher(IEventAggregator eventAggregator)
   {
      this.eventAggregator = eventAggregator;
   }
 
   public void PublishEvent()
   {
      this.eventAggregator.Publish(new MyEvent());
   }
}

取消订阅和弱绑定

由于IEvnetAggregator是一种弱绑定,并不需要显示取消订阅。如果需要也可以取消:

IEventAggregator.Unsubscribe(this);

同步和异步发布

默认IEventAggregator.Publish方法是同步发布事件的,也可以调用PublishOnUIThread调度异步发布到UI线程,或者调用PublishWithDispatcher进行异步调度。

通道

订阅者可以监听特定的通道,发布者也可以发布事件到特定的通道。如果一个事件发布到特定的通道里,只有订阅了该通道的订阅者才能收到该事件。这在同一信息在多个不同的Context使用时特别有用。

通道是一个字符串,允许订阅者与通道,发布者与通道的松耦合。

默认情况下,Subscribe()方法将订阅单一通道的事件,EventAggregator.DefaultChannel。类似的Publish()也是发布事件到的通道。当然可以指定自己的通道。

订阅到通道

想要订阅到特定的通道,给Subscribe方法传参:eventAggregator.Subscribe(this, "ChannelA")。也可以订阅多个通道:eventAggregator.Subscribe(this, "ChannelA", "ChannelB")。指定通道的情况下,默认通道将不起作用。

发布到通道

与订阅到通道类似,不再赘述。

取消通道中的订阅

eventAggregator.Unsubscribe(this, "ChannelA")表示取消订阅channelA通道的事件,eventAggregator.Unsubscribe(this)表示取消所有通道的事件。

使用自己的IoC容器

如果使用默认的Bootstrapper,即StyletIoC,EventAggregator 已经默认配置;

但是,如果您使用的是其他 IoC 容器,则需要确保 EventAggregator 已注册为IEventAggregator接口的单例服务 - 必须只创建一个 EventAggregator 实例,并且每次请求时都必须返回此一次实例。

原文地址:https://www.cnblogs.com/qouoww/p/15797312.html