Thursday, February 1, 2018

Event Aggregator

Problem in traditional approach of event Handling

1. Tight coupling will not allow publisher and subscriber to change independently of each other.
2. The subscriber of the event needs to know the publisher of an event and refer it directly by event names causing a tight coupling between them.
3. If there are multiple subscriber and publisher then code becode hard to read and debug.
4. Its Subscriber responsibility to register and unregister from an event, And if subscriber forgets to unregister
than it will be memory leak because both subscriber and publisher will remain in memory.


Benefit of Event Aggregator

1. Simply subscribing and unsubscribing  to events.
2. Decouple publisher from subscribers allowing both to change without effecting the other.
3. Make it easy to add events.
4. Centralized handling of events.
5. Reduce wastage of system resources. ( not clear how)


Publish event using Prism (It is simulate to fire event)

PersonViewModel
public Person SelectedPerson 

get

return this.selectedPerson; 
}
set

if(this.selectedPerson!=value)

this.selectedPerson = value;
this.NotifyPropertyChanged("SelectedPerson");

// Publish event.
this
.iEventAggregator
.GetEvent<PubSubEvent<Person>>()
.Publish(this.SelectedPerson);
}
}
}

Subscribe event using Prism

class name is PersonViewModel

private IEventAggregator iEventAggregator;
public PersonDetails1ViewModel(IEventAggregator iEventAggregator)

this.iEventAggregator = iEventAggregator;
SubscriptionToken subscriptionToken =
this
.iEventAggregator
.GetEvent<PubSubEvent<Person>>()
.Subscribe((details) =>
{
this.Person = details;
});

this.Subscribe = new DelegateCommand(
() =>
{
subscriptionToken =
this
.iEventAggregator
.GetEvent<PubSubEvent<Person>>()
.Subscribe((details) =>
{
this.Person = details;
});
});

this.Unsubscribe = new DelegateCommand(
() => {

this
.iEventAggregator
.GetEvent<PubSubEvent<Person>>()
.Unsubscribe(subscriptionToken);
});
}

Another way to subscribe
private IEventAggregator iEventAggregator;
public PersonDetails2ViewModel(IEventAggregator iEventAggregator)
{
this.iEventAggregator = iEventAggregator;
this
.iEventAggregator
.GetEvent<PubSubEvent<Person>>()
.Subscribe((details) =>
{
this.Person = details;
});
}

In view we have to pass

this.DataContext = new PersonViewModel(Event.EventInstance.EventAggregator);

No comments:

Followers

Link