Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

Listener pattern - there are two ways I can implement it, which one?

I have an android app. In it user details (name, email, sex, preferences, stats) are downloaded right after login.

I have a Downloader Class that executes the API call and receives the data and then it stores all the user data in a UserDataAndStats class.

I have an interface IOnUserDetailsReceivedListener and each class interested in the data can implement it and receive the user data.

I need the user details in a few places. There are two ways I can play this out:

a) make all the activities interested in the user data implement the IOnUserDetailsReceivedListener and in the method onUserDetailsAndStatsReceivedListener, they can get the values for each variable

b) make one class implement this interface, get the values of the data and store it in app-wide variables, that I can later access by calling that class and its getter

How should I proceed?

Upvotes: 1

Views: 37

Answers (1)

Rob
Rob

Reputation: 11733

Of course with some variation on the former. This is kind of a good example of what Reactive Programming is all about. You have an event. Just processing it and then letting any interested party have access to an entity that embodies its state is fraught with peril. For one, you have to deal with concurrency. Updates while access is occurring or multiple updates. But there is also just the fact that the state version tends to end up being much uglier. Why? Because your code will then start filling up with things deciding what to do based on a lot of testing of conditions, and those conditions can become chaotic very fast. For example, an object with a few properties, which could have potentially n different states, can then, by definition, be in one of n to some power states (exponential complexity problem).

As much as possible, have objects keep track of their own state only.

Also, consider using some synthetic events. For instance, you might have some consumers who are just interested in the arrival of the message, others in some more processed form, so you could have a handler listening for arrival, reforming the item, and then broadcasting another message with a more processed, domain-focused entity for downstream consumption.

Upvotes: 1

Related Questions