官术网_书友最值得收藏!

Event aggregator

An event aggregator (also known as publisher/subscriber or Pub-Sub) is a messaging pattern where senders of messages/events, called publishers, do not program the messages to be sent directly to a single/specific receiver, called subscribers, but, instead, categorize published messages into classes without knowledge of which subscribers, if any, there may be. Messages are then funneled through a so-called aggregator and delivered to the subscribers. This approach provides a complete decoupling between the publishers and subscribers while maintaining an effective messaging channel.

Event aggregator implementation within the Xamarin.Forms framework is done via MessagingCenterMessagingCenter exposes a simple API that is composed of two methods for subscribers (that is, subscribe and unsubscribe) and one method for publishers (send).

We can demonstrate the application of the event aggregator pattern by creating a simple event sink for service communication or authentication issues in our application. In this event sink (which will be our subscriber), we can subscribe to error messages that are received from various view-models (given that they all implement the same base type) and alert the user with a friendly dialog:

MessagingCenter.Subscribe<BaseViewModel> (this, "ServiceError", (sender, arg) =>
{
// TODO: Handler the error
});

We would have the following in the event of an unhandled exception on our view-model:

 public void Login()
{
try
{
//TODO: Login
Result = "Successfully Logged In!";
}
catch(Exception ex)
{
MessagingCenter.Send(this, "ServiceError", ex.Message);
}
}
主站蜘蛛池模板: 海阳市| 三明市| 堆龙德庆县| 务川| 怀安县| 长治市| 桂阳县| 鄂托克前旗| 包头市| 鄢陵县| 蒲城县| 新巴尔虎右旗| 阿克苏市| 台前县| 延川县| 崇明县| 溆浦县| 潞西市| 崇文区| 久治县| 仲巴县| 凤庆县| 富民县| 青州市| 道真| 长葛市| 靖远县| 汉川市| 余干县| 明星| 贞丰县| 海伦市| 章丘市| 高邑县| 调兵山市| 石家庄市| 大庆市| 临颍县| 阳谷县| 苏尼特右旗| 商都县|