Issue
I am passing SessionManager as Dependency that require context in my ViewModel
val viewModel = ViewModelProvider(this, ListingsViewModelFactory(
ListingsModel(1),
SessionManager(
requireContext(), <===== HERE
JsonEncoder(),
JsonDecoder()),
Validator(),
WebService(),
JsonEncoder(),
JsonDecoder()
)
).get(ListingsViewModel::class.java)
we know that passing context to ViewModel is a bad practice that should cause memory leaks.
- So can we pass context in dependency in ViewModel like currently i'm passing in SessionManager?
- Passing context in Dependency in ViewModel cause memory leaks?
Thanks for all the answers.
Solution
When you call requireContext()
in a Fragment, it is actually getting the Activity instance, and passing that to the ViewModel will leak the Activity.
It is safe to pass the application Context, because that is a single instance for the lifetime of your application.
So replace requireContext()
with requireContext().applicationContext
, and it is fine.
It seems a bit odd that you are instantiating your JsonEncoder and Decoder twice, but maybe it's OK with your logic. You might want to check that.
Answered By - Tenfour04
Answer Checked By - Candace Johnson (JavaFixing Volunteer)