如何在addOnCompleteListener Firebase上返回值?

我有一个登录活动连接到我的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))
        }
    }
}

更新:

我的课程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
    }
}

我的班级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)
        }
    }
}

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

评论
莫小柒i
莫小柒i

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

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

change return Result.Success(user) to gotResult(user)

希望这可以帮助

点赞
评论