在Firebase身份验证中使用signInWithEmailAndPassword时如何使用协程?

Bas*_*ngs 1 android kotlin firebase firebase-authentication kotlin-coroutines

我想在 firebase 中使用协程来实现登录功能

 private suspend fun signin() {

    var email = binding.emailArea.text.toString()
    var password = binding.passwordArea.text.toString()
    return withContext(Dispatchers.IO) {
        auth.signInWithEmailAndPassword(email,password).await()
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不知道签名函数真正返回什么。

CoroutineScope(Dispatchers.IO).launch {
    val result = async { signin() }
    //how to utilize result?
}
Run Code Online (Sandbox Code Playgroud)

我知道等待返回被推迟。但我不知道如何使用这个功能。

Ser*_*gey 5

awaitis 方法返回一个函数对象TasksuspendAuthResultsignInWithEmailAndPassword

private suspend fun signIn(): AuthResult? {
    try {
            // ... init email and password


            val authResult: AuthResult = signInWithEmailAndPassword(email,password).await()
            return authResult
            
        } catch (e: Exception) {
            return null
        }
}

someCoroutineScope.launch { // launching a coroutine
    val authResult: AuthResult? = signIn()
    if (authResult == null) {
        // handle error
    } else {
        // use authResult for example to get FirebaseUser using authResult.getUser()
    }  
}
Run Code Online (Sandbox Code Playgroud)

要在 Android 中启动协程,我们可以在类中或/中someCoroutineScope使用。viewModelScopeViewModellifecycleScopeActivityFragment