Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I cache data from SharedPreferences in my activity?

I'm working on a GCM based application where the user can subscribe to several topics.

I need to know which topics the users is subscribed to in two places:

  • Main activity - to show Subscribe or Unsubscribe buttons in the UI
  • GCM listener service - to filter messages and handle "obsolete" subscriptions via GcmPubSub. Basically, if the listener gets a message for the topic which is not in the app's list of topics then probably we have an "obsolete" subscription on the GCM server and have to unsubscribe.

So basically I have an activity and a service which both acces some common data and both can modify this data.

I've read that one of the options to share data between an activity and a service is to use shared preferences:

  • Sharing data amongst activities and services

This is suitable for my case as I'd be quite content to share Set<String> which SharedPreferences support. Users will be probably interested in just a few topics (say, max. 10).

Here's my code to check if the user is subscribed to a topic:

SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
Set<String> subscribedTopics = preferences.getStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, Collections.<String>emptySet());
boolean subscribedForTopic = subscribedTopics.contains(topic);

Here's the code to modify the subscription (for instance unsubscribe):

SharedPreferences preferences =
        PreferenceManager.getDefaultSharedPreferences(getContext());
Set<String> topics = new TreeSet<String>(preferences.getStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, Collections.<String>emptySet()));
topics.remove(topic);
preferences.edit().putStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, topics).apply();

But now I've got my doubts, if it is an appropriate way. I'll be basically accessing shared preferences for every check (in the UI or on received message) as well as on modifications.

Is this the right way to go? Should I share data between the activity and the service directly via preferences or should I somehow cache values?

like image 321
lexicore Avatar asked Jan 06 '23 20:01

lexicore


1 Answers

There is no need for you to cache SharedPreferences data, as SharedPreferencesImpl already caches the shared data.

like image 159
cybersam Avatar answered Jan 25 '23 16:01

cybersam