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.
CodePudding user response:
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.
CodePudding user response:
I assume it depends on the type of context. Since the lifetime of a ViewModel is longer than the lifetime of the view it refers to, passing Activity can cause memory leak.
However, the lifetime of a ViewModel cannot be longer than the lifetime of the application. So the passing of Application should be fine.