我正在寻找对诸如 onComplete(), onFailure()
的事件的反应方法,例如在ViewModel内部。
例如:
我已经创建了一个名为emailsignInservice的类,该类在用户登录时从firebase实例中调用OnCompleteListener
。我想在ViewModel中处理此事件以更新UI。
emailsignInservice
fun signInUser(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password).
addOnCompleteListener(OnCompleteListener<AuthResult> { task -> {
if(task.isSuccessful) {
val currentUser = auth.currentUser;
// inform somehow viewmodel to change UI state later
} //...
} });
}
loginViewModel
class LoginViewModel : ViewModel() {
var userName: String? = null; //...
var userPassword: String? = null; //...
// Button on click
fun LoginUser() {
// Create an instance of signin service and get result to inform UI
}
一个选项是创建一个接口并将其作为参数传递给EmailSignInService
(回调),然后在addOnCompleteListener
中调用相应的方法。LoginViewModel
还必须实现接口,并将逻辑放入相应的方法中。
是否有另一种或更好的方法来处理这种情况?
您真的不想处理ViewModel中的firebase事件。ViewModel不应该了解数据源的实现详细信息。假设对您的数据源的抽象作用,通常是通过具有所有实现详细信息的存储库对象所揭示的livedata对象。Livedata可以将数据从firebase任务对象委托回Viutmodel。
非常粗糙的设计(您的应该更强大并处理错误):
data class UserData {
// information about the logged in user, copied from FirebaseUser
}
class UserRepository {
fun newUser(): LiveData<UserData> {
// Sign in with Firebase Auth, then when the Task is
// complete, create a UserData using the data from
// the auth callback, then send it to the LiveData
// that was returned immediately
}
}
class LoginViewModel : ViewModel() {
private val repo = UserRepository()
fun signInNewUser() {
val live: LiveData<UserData> = repo.newUser()
// observe the LiveData here and make changes to views as needed
}
}