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

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);
}
}
主站蜘蛛池模板: 冀州市| 嵊泗县| 临武县| 青川县| 怀化市| 交口县| 阳高县| 伊宁县| 利川市| 五常市| 大同市| 博爱县| 额敏县| 雷山县| 集贤县| 桃江县| 六盘水市| 安福县| 盐源县| 武威市| 九江县| 琼结县| 镇安县| 门源| 镶黄旗| 漳州市| 厦门市| 雅江县| 蓝田县| 白朗县| 昆明市| 平南县| 库尔勒市| 绥芬河市| 祁东县| 伊春市| 阿坝| 绥棱县| 工布江达县| 贺州市| 托克托县|