我有一个登录活动,该活动使用电子邮件和密码实施Firebase身份验证。它的作用是将用户输入的电子邮件和密码发送给FirebaseAuth函数,并通过LiveData检索响应,然后观察它。
问题是,当登录失败或凭据无效时,它应该祝酒一条消息,但是真正发生的是它祝酒了多次,也许超过了4次(这使祝酒显示了很长时间)。] >
LoginActivity
private fun signInWithEmailAndPassword(email: String, password: String){ val authResult = viewModel.authWithEmailPassword(email, password) handleAuthenticationResult(authResult) } private fun handleAuthenticationResult(authResult: LiveData<Resource<AuthResult>>){ authResult.observe(this, object : Observer<Resource<AuthResult>>{ override fun onChanged(it: Resource<AuthResult>?) { when(it){ is Resource.Loading -> { toggleLoadingIndicator(true) } is Resource.Success -> { toggleLoadingIndicator(false) val isNewUser = it.data.additionalUserInfo?.isNewUser ?: true if(isNewUser) gotoIntroActivity() else gotoMainActivity() } is Resource.Failure -> { toggleLoadingIndicator(false) when(it.throwable){ is FirebaseAuthException -> Toast.makeText(this@LoginActivity, getString(R.string.error_credentials_invalid), Toast.LENGTH_SHORT).show() else -> Toast.makeText(this@LoginActivity, getString(R.string.error_login_failed), Toast.LENGTH_SHORT).show() } } } } }) }
ViewModel
fun authWithEmailPassword(email: String, password: String): LiveData<Resource<AuthResult>>{ return AuthRepository.signInWithEmailAndPassword(email, password) }
FirebaseAuth
private var authResult: MutableLiveData<Resource<AuthResult>> = MutableLiveData() fun signInWithEmailAndPassword(email: String, password: String): LiveData<Resource<AuthResult>>{ authResult.value = Resource.Loading() mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener{ if(it.isSuccessful) authResult.value = Resource.Success(it.result!!) else authResult.value = Resource.Failure(it.exception!!) } return authResult }
资源
sealed class Resource<out T> { class Loading<out T> : Resource<T>() data class Success<out T>(val data: T) : Resource<T>() data class Failure<out T>(val throwable: Throwable) : Resource<T>() }
为什么会这样,如何解决?我应该在每次触发
Resource.Failure
时都删除观察者吗?
我有一个登录活动,该活动使用电子邮件和密码实施Firebase身份验证。它的作用是将用户输入的电子邮件和密码发送给FirebaseAuth函数并检索响应...
LiveData是您创建并只能订阅一次的东西。就您而言,您每次获得身份验证结果时都会订阅它,因此会发生多个重复事件。