Ozuf Ozuf - 2 months ago 6
Android Question

What will happen when I call Class.getInstance for an already Instantiated classs?

What will happen when I call two Class.getInstance twice in the same method?

For example:

private void widgetListeners() {
notifyNews.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (notifyNews.isChecked()) {
FirebaseMessaging.getInstance().subscribeToTopic(getString(R.string.news_subscriber));
} else {
FirebaseMessaging.getInstance().unsubscribeFromTopic(getString(R.string.news_subscriber));
}
return true;
}
});
notifyVersion.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (notifyVersion.isChecked()) {
FirebaseMessaging.getInstance().unsubscribeFromTopic("Version");
} else {
FirebaseMessaging.getInstance().unsubscribeFromTopic(Version"));
}
return true;
}
});
}


Would it better if I call
FirebaseMessaging.getInstance()
once at the top of the
widgetListeners()
method body and store it in a variable or I just call in each
onPreferenceChange
or I stick to what I've already done above?

Note: I call
widgetListeners()
in
onCreateView
of a fragment that extends the
PreferenceFragment
class.

Answer

getInstance() is usually an artifact of the singleton pattern. From a high level, that means you only ever access one instance of this class, which is created the first time you access it.

What you've already done should work well. The instance is already stored for you, so there's really no need to store it in another reference in your case.