Search code examples
javaandroidstaticobservableobservers

Make 'static' class observable


I have a class Settings with static methods which I use to save and load my data. This is for example the Save() method:

public static void Save(SETTING_KEY key, String value)
{
    SharedPreferences sp = _context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();

    editor.putString(key.toString(), value);
    editor.commit();    
}

Now I'd like to make the class Settings observable. The problem is that extending my Settings-class from Observable does not work, as I don't instantiate this class as I only use its static methods.

Is there any easy way to make this static class observable?


Solution

  • Add your own observer mechanism. Simple implementation below

    public interface Observer {
        void onSettingsChanged(String key, String value);
    }
    
    private static Observer observer;
    public static void setObserver(Observer observer_) {
        observer = observer_;
    }
    
    public static void Save(SETTING_KEY key, String value) {
        SharedPreferences sp = _context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
    
        editor.putString(key.toString(), value);
        editor.commit();
        if (observer != null) {
            observer.onSettingsChanged(key, value);
        }
    }
    

    You could also use a List<Observer> if you need more than 1 and you can also use some sort of event bus (e.g. Otto) system to publish events without having to provide a direct observer mechanism.