https://kotlinlang.org logo
#android
Title
# android
z

Zaki Shaikh

02/28/2023, 10:18 AM
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

Alexej Hlinka

02/28/2023, 11:21 AM
why do you need context in repository ? ....honestly i would avoid passing context to non-ui layers at all costs 😄
c

chanjungskim

02/28/2023, 11:24 AM
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

Zaki Shaikh

02/28/2023, 11:27 AM
I need to access shared preferences in repository so how can I do this?
c

chanjungskim

02/28/2023, 11:28 AM
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

Zaki Shaikh

02/28/2023, 11:44 AM
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

chanjungskim

02/28/2023, 11:46 AM
If you use hilt, it doesn't lead memory leak
z

Zaki Shaikh

02/28/2023, 12:31 PM
Yes I am using hilt
s

Sam Pengilly

02/28/2023, 11:33 PM
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
11 Views