Hi everyone, I want to know that we can't pass `C...
# android
z
Hi everyone, I want to know that we can't pass
Context
in viewModel parameter as it leads to memory leak but if I have a viewModel and A repository in its constructor injection so can I inject context in repository and if yes then why it won't lead to memory leak as it does in viewModel. Thank you
😶 1
a
why do you need context in repository ? ....honestly i would avoid passing context to non-ui layers at all costs 😄
c
Not only viewModel but most of it.
Not only context but also all the things that can be connected to other class such as Listener.
you can inject context with di library. But you should reconsider if you really need the context for the business logic. Context is normally, for intents, accessing resources or managers, services, etc.
z
I need to access shared preferences in repository so how can I do this?
c
You can inject context to the Preference class.
And inject the preference class into the ViewModel. Then you won't need context in viewmodel
z
Yes but if I am injecting which is using context and pref class is being used in repository and repository in viewModel so does lead to memory leak or not, I just want to know.
c
If you use hilt, it doesn't lead memory leak
z
Yes I am using hilt
s
I think more specifically it doesn’t lead to leaks because: 1. It’s the application context that’s being injected, not an activity context (which could leak if the activity is destroyed whilst the viewmodel lives on) 2. Dagger/Hilt manages the lifecycle of components according to the scopes used. Creating a singleton of some retrofit service built using an application context is normal and won’t lead to leaks. It’s something that is expected to live for the whole application lifecycle
❤️ 1