architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[todo-mvvm-rx]Having a reference to Context in ResourceProviders might leak memory?

Open mspmax opened this issue 7 years ago • 1 comments

Hi @florina-muntenescu I noticed that in ResourceProvider there's a reference to the context. Will this be leaking memory? or how is this handled? should it be handled at all?

mspmax avatar Jan 25 '18 00:01 mspmax

What’s in ResourceProvider In the Google TODO samples, ResourceProvider is usually something like:

public class ResourceProvider { private final Context context;

public ResourceProvider(@NonNull Context context) {
    this.context = context;
}

public String getString(@StringRes int resId) {
    return context.getString(resId);
}

} The concern is that keeping a Context reference could prevent it from being garbage collected.

Will this leak memory? It depends on which context is stored:

If you pass an Activity context → Yes, you can leak the Activity if ResourceProvider lives longer than the Activity lifecycle (e.g., in a singleton ViewModel or static object).

If you pass the Application context → No leak risk. The Application context lives for the lifetime of the app and is safe to store.

Best practice fix Always inject the Application context into ResourceProvider.

Example in Dagger/Hilt or manual DI:

public ResourceProvider(Application application) { this.context = application; } Or, if you only have an Activity context available, convert it to the Application context before storing:

this.context = context.getApplicationContext(); Why it matters in MVVM In MVVM, ResourceProvider is often injected into the ViewModel. Since ViewModels survive configuration changes (rotation, etc.), storing an Activity context inside them can easily cause a memory leak. Using the Application context avoids this entirely.

Summary

Store only the Application context in ResourceProvider.

Never store an Activity or Fragment context in long-lived objects.

With Application context, no extra leak handling is required.

VaradGupta23 avatar Aug 08 '25 12:08 VaradGupta23