I am making an app with firebase authentication that uses signInWithEmailAndPassword()
to authenticate the users. Now I also need the activity context with signInWithEmailAndPassword()
. So, how do I pass the activity context in my viewmodel class?
class LoginViewModel: ViewModel() {
var auth: FirebaseAuth = FirebaseAuth.getInstance()
fun signIn(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(..context required..) { task ->
}
}
}
I have already gone through almost all questions related to my query and everyone in the answers come to the conclusion that using ActivityViewModel()
instead of ViewModel()
and getting application context is the way to go. But as I understand ApplicationContext won’t respond to configuration changes, so I don't think this is the way to go. The most popular question on SO with the same query is this. But they also said to use application context. So I thought of using a dependency injection framework like Dagger/HILT to inject the context that I need. Now my question is, will the DI framework take care of the activity context once the activity is destroyed and avoid any memory leaks?
Ideally, your viewmodel does not have a reference to its hosting activity, as that invites memory leaks and configuration change problems.
Also, bear in mind that the sign-in flow involves navigation to an externally-supplied UI. Usually, navigation is managed by the UI layer (activity, fragment, or composable), perhaps acting on instructions from a viewmodel.
So, I would have your signInWithEmailAndPassword()
call and the addOnCompleteListener()
call be made in the UI layer. The on-complete listener could call a function on the viewmodel to inform it of the successful result, if desired.