Anyone can detail the pros and cons to pass data from one class to another using event mechanism? When is the best time to use event to pass data?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s take an example. You have a system where 20 people are subscribed to a weather station for changes in weather. Do you want the weather station to keep track of all the people and services that are subscribed?
In my opinion the weather station should not know anything about the people or services that are waiting for weather changes. The weather station should just dispatch an event, and whoever is listening to it will get notified 🙂
So the point is, you use events to notify observers about an action or state change that occurred in the object. Observers can be difference type of objects since you don’t have to know anything about them. If someone listens to the object, then he takes care of it.
If it was one to one relation and the object waiting for something to happen is always of the same type, then you wouldn’t really need an event for that case.
Events are also great to decouple systems, like seen in my example above with the weather station. The weather station can run on its own without knowing about the services or users that are listening to it.