gpt4 book ai didi

android - 如何在addOnCompleteListener Firebase上返回值?

转载 作者:行者123 更新时间:2023-12-02 13:30:43 25 4
gpt4 key购买 nike

我有一个登录 Activity 连接到我的Firebase应用程序。我想在完整的侦听器上返回一个值。

class LoginDataSource {

private lateinit var user: LoggedInUser

fun login(username: String, password: String, mAuth: FirebaseAuth): Result<LoggedInUser> {
try {
mAuth.createUserWithEmailAndPassword(username, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Sign in success, update object with the signed-in user's information
val currentUser = mAuth.currentUser
if (currentUser != null) {
user = LoggedInUser(currentUser.uid, currentUser.email!!)
}
return Result.Success(user)
} else {
// If sign in fails, display a message to the user.
Log.d("Login", "createUserWithEmail:failure")
}
}

return Result.Success(user)
} catch (e: Throwable) {
return Result.Error(IOException("Error logging in", e))
}
}
}


更新:

我的类(class)LoginRepository
class LoginRepository(val dataSource: LoginDataSource) {

fun login(username: String, password: String, mAuth: FirebaseAuth): Result<LoggedInUser> {
// handle login
val result = dataSource.login(username, password, mAuth)

if (result is Result.Success) {
setLoggedInUser(result.data)
}

return result
}
}

我的类(class)LoginViewModel
class LoginViewModel(private val loginRepository: LoginRepository) : ViewModel() {

private val _loginForm = MutableLiveData<LoginFormState>()
val loginFormState: LiveData<LoginFormState> = _loginForm

private val _loginResult = MutableLiveData<LoginResult>()
val loginResult: LiveData<LoginResult> = _loginResult

fun login(username: String, password: String, mAuth: FirebaseAuth) {
// can be launched in a separate asynchronous job
val result = loginRepository.login(username, password, mAuth)

if (result is Result.Success) {
_loginResult.value = LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
} else {
_loginResult.value = LoginResult(error = R.string.login_failed)
}
}
}

这些代码是首次创建应用程序时来自“ Activity 登录”的模板。有什么建议吗?

最佳答案

您可以调用一个函数,而不是在侦听器中返回值

fun gotResult(user: LoggedInUser){
// you can do your logic here, once you get the result
}

return Result.Success(user)更改为 gotResult(user)
希望这可以帮助

更新:

当您使用viewmodel和livedata时,可以将livedata传递给登录调用
fun login(username: String, password: String, mAuth: FirebaseAuth, user: MutableLiveData<LoggedInUser>)
您的 LoginViewModel将订阅此数据,并且 LoginDataSource将在onComplete上对其进行更改

关于android - 如何在addOnCompleteListener Firebase上返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com