Home > Net >  How to use Coroutines while using ```signInWithEmailAndPassword``` in firebase realtimeDatabase?
How to use Coroutines while using ```signInWithEmailAndPassword``` in firebase realtimeDatabase?

Time:11-01

I want to use coroutines in firebase for sign in function

 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()
    }
}

but I don't know what signing function really return.

CoroutineScope(Dispatchers.IO).launch {
    val result = async { signin() }
    //how to utilize result?
}

I know that await returns deferred. But I don't know how to utilize this function.

CodePudding user response:

The await method on Task is suspend and returns an AuthResult object for signInWithEmailAndPassword function:

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()
    }  
}

To launch a coroutine in Android instead of someCoroutineScope we can use viewModelScope in a ViewModel class, or lifecycleScope in Activity/Fragment.

  • Related