我想在 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()
}
}
但我不知道真正回傳什么簽名功能。
CoroutineScope(Dispatchers.IO).launch {
val result = async { signin() }
//how to utilize result?
}
我知道等待回傳延遲。但我不知道如何利用這個功能。
uj5u.com熱心網友回復:
await方法Task是suspend并回傳一個函式AuthResult物件:signInWithEmailAndPassword
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()
}
}
要在 Android 中啟動協程而不是someCoroutineScope我們可以viewModelScope在ViewModel類中或/lifecycleScope中使用。ActivityFragment
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/524656.html
標籤:Google Cloud Collective 安卓火力基地科特林firebase 身份验证kotlin 协程
