Search code examples
androidkotlingoogle-signincredential-manager

Android Kotlin - Credential Manager sign in - coroutineScope


I'm trying to implement the new sign in method since the old one is what what ever the hell reason deprecated, but the google docs are as always incomplete.

This is the part I'm current at:

coroutineScope.launch {
    try {
        val result = credentialManager.getCredential(
            request = request,
            context = this,
        )
        handleSignIn(result)
    } catch (e: GetCredentialException) {
        handleFailure(e)
    }
}

coroutineScope is unresolved referrence

I'm watching this tutorial: https://www.youtube.com/watch?v=P_jZMDmodG4

and the guy there just does:

val coroutineScope = rememberCoroutineScope()

and it works for him, but for me rememberCoroutineScope() is also unresolved referrence

How to make it work?

Thanks in advance

EDIT:

Based on Tenfour04's answer, I tried this now:

    val credentialManager = CredentialManager.create(this)

    val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
        .setFilterByAuthorizedAccounts(false)
        .setServerClientId("blaaaa")
        .build()

    val request: GetCredentialRequest = GetCredentialRequest.Builder()
        .addCredentialOption(googleIdOption)
        .build()

    lifecycleScope.launch {
        whenStarted {
            try {
                val result = credentialManager.getCredential(
                    request = request,
                    context = this@GoogleLogin,
                )
                handleSignIn(result)
            } catch (e: GetCredentialException) { Log.d("pikaboo", "I love google")}
        }
    }

but it doesn't start the login process


Solution

  • rememberCoroutineScope() is what you would use in a Compose Composable. If you are not using Compose, then if you are in an Activity or Fragment, use lifecycleScope, and if you’re in a ViewModel, use viewModelScope.

    From what I can gather from your other questions, you are not using Compose, and therefore cannot successfully use @Composable. It doesn’t make sense. Compose is a completely different UI system than the traditional views you are using.