2

I'm learning how to login firebase with MVVM and I don't know where to put AuthStateListener. I placed login and registration in the repository, but I don't know where to place the AuthStateListener according to the MVVM pattern. I was thinking about activity, but on the other hand it is logic, so it should probably be in the repository

LoginRepository:

class LoginRepository @Inject constructor(private val firebaseAuth: FirebaseAuth) {


fun signIn(email: String, password: String) = Completable.create{ emitter ->
    firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener {
        if (emitter.isDisposed) {
            if (it.isSuccessful) {
                emitter.onComplete()
                Log.e("LoginRepository", "Ok")
            } else
                emitter.onError(it.exception!!)
            Log.e("LoginRepository", "Error")
        }
    }
}

fun signInWithGoogle(authCredential: AuthCredential) = Completable.create { emitter ->
    firebaseAuth.signInWithCredential(authCredential).addOnCompleteListener {
        if (emitter.isDisposed) {
            if (it.isSuccessful)
                emitter.onComplete()
            else
                emitter.onError(it.exception!!)
        }
    }
}

fun logOut() = firebaseAuth.signOut()

AccountViewModel:

class AccountViewModel @Inject constructor(private val loginRepository: LoginRepository): ViewModel() {

    fun logout() {
        loginRepository.logOut()
    }
}

LoginActivity:

class AccountActivity : DaggerAppCompatActivity() {

    lateinit var accountViewModel: AccountViewModel

    @Inject
    lateinit var factory: ViewModelProvider.Factory

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_account)

        accountViewModel = ViewModelProviders.of(this, factory).get(AccountViewModel::class.java)

        log_out_button.setOnClickListener {
            logOut()
        }
    }

    private fun logOut() {
        accountViewModel.logout()
    }
}
Ashish
  • 6,791
  • 3
  • 26
  • 48
beginner992
  • 659
  • 1
  • 9
  • 28
  • 4
    I think it's a little too broad but if you are interested in a clean Firebase authentication, you can check this [article](https://medium.com/firebase-tips-tricks/how-to-create-a-clean-firebase-authentication-using-mvvm-37f9b8eb7336). You'll see where to put the auth listener. – Alex Mamo Nov 22 '19 at 11:45
  • Thank you. I hope his way is fine – beginner992 Nov 22 '19 at 11:55

0 Answers0