Search code examples
androidfirebasekotlinmvvmandroid-jetpack

Firebase authentication with MVVM kotlin


I m new in MVVM and jetpack library. i have an simple application of firebase Authentication , Registration and login. i try many code but i am not getting flow for view Model and repertory. so any one can convert this code with view model and how it works.

Here is code for login

  auth = FirebaseAuth.getInstance()

  fun login(view: View){
        var email:String = binding.editTxtEmail.text.toString()
        var password:String = binding.editTxtPassword.text.toString()

        auth.signInWithEmailAndPassword(email,password).addOnCompleteListener { task ->
                if(task.isSuccessful){
                    val intent= Intent(this,MainActivity::class.java)
                    startActivity(intent)
                    finish()
                }
            }.addOnFailureListener { exception ->
                Toast.makeText(applicationContext,exception.localizedMessage, Toast.LENGTH_LONG).show()
            }
        }

Solution

  • First, you need to add a ViewModel and then add two methods in the ViewModel that accept email and passwords like this.

    class AuthViewModel: ViewModel() {
    
    fun handleSignIn(email: String, password: String) {
    
    }
    
    fun handleSignUp(email: String, password: String, confirmPassword: String) {
    
    }
    }
    

    Then you need to add an enum or sealed class to represent the possible states of your login flow, here is an example:

    sealed class AuthState {
    object Idle : AuthState()
    object Loading : AuthState()
    object Success : AuthState()
    class AuthError(val message: String? = null) : AuthState()
    }
    

    Then you need to add an observable state and expose it as LiveData like this:

     private val _authState by lazy { MutableLiveData<AuthState>(AuthState.Idle) }
    val authState: LiveData<AuthState> = _authState
    

    With that added you can now update your methods to handle sign and sign up like this:

    fun handleSignUp(email: String, password: String, confirmPassword: String) {
        if (!isEmailValid(email)) {
            _authState.value = AuthState.AuthError("Invalid email")
            return
        }
        if (password != confirmPassword) {
            _authState.value = AuthState.AuthError("Password does not match")
            return
        }
        FirebaseAuth.getInstance().createUserWithEmailAndPassword(
            email, password)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    Log.i(TAG,"Email signup is successful")
                    _authState.value = AuthState.Success
                } else {
                    task.exception?.let {
                        Log.i(TAG,"Email signup failed with error ${it.localizedMessage}")
                        _authState.value = AuthState.AuthError(it.localizedMessage)
                    }
                }
            }
    }
    

    You can then listen to the list

    val authState by viewModel.authState.observeAsState(AuthState.Idle)
    

    Good luck.