Reputation: 22008
I guess everybody knows the listener interface pattern. I have a class with some favorite items the user can add or remove.
In this class I have:
public static OnFavsChangedListener onFavsChangedListener;
public interface OnFavsChangedListener {
abstract void onFavsChanged();
}
public static void setOnFavsChangedListener(
OnFavsChangedListener listener) {
onFavsChangedListener = listener;
}
public void addToFavorites () {
if (onFavsChangedListener != null) {
onFavsChangedListener.onFavsChanged()
}
}
This works great when I only need to use ONE of those listeners, when I use setOnFavsChangedListener
from different Activities
, they will overwrite the last one.
My idea was to use an ArrayList
of listeners and call them all when my Favs change, but it's hard to not let the ArrayList
grow too big (Activities
might add a listener on every orientation change / onCreate
). I could use a HashMap
of IDs and listeners, let every Activit
y remove it's listener onDestroy
, but that seems clumsy.
TL;DR: Whats an elegant way for several Activities
to be informed when my Favs change?
Upvotes: 1
Views: 1311
Reputation: 6761
This may be overkill for your use case, but for notifying classes about events I use an event bus (specifically https://github.com/greenrobot/EventBus).
This allows you to simply post a message and every class that has registered to receive that type of message gets it. Very simple to use, and pretty small as far as libraries go.
Upvotes: 3