Home > Net >  how to use firebase authentication instance in viewModel
how to use firebase authentication instance in viewModel

Time:02-24

I'm new at the Firebase. I want to use Firebase authentication in my project. Based on the Firebase documents, the user can sign in using this piece of code:

auth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "signInWithEmail:success")
            } else {
                Log.w(TAG, "signInWithEmail:failure", task.exception)
            }
        }

And has attached a listener to handle successfully sign in or failure.

My problem is:

I'm using ViewModel. So I implemented this code in ViewModel, but the listener needs activity or executor to be attached to. But I don't have any. is it safe to inject activity in the ViewModel? ( as far as I know, we shouldn't do that because of life cycle stuff) if not, how can I solve the problem?

CodePudding user response:

My problem is: I'm using ViewModel.

That's not a problem. That's a solution because it allows the data to survive configuration changes such as screen rotations.

but the listener needs activity or executor to be attached to.

If you are using a listener, yes indeed it does. But since you are using Kotlin, it makes more sense to me to use Kotlin Coroutines and to suspend a function using await() until the async operation completes.

is it safe to inject activity in the ViewModel?

No, this is not how separation of concerns works.

In my opinion, the best option that you have is to use the MVVM architecture pattern. I have even written an article regarding this topic, called:

It's about Firebase Anonymous authentication but the same rules apply in case of the authentication with email and password.

  • Related