Search code examples
androidkotlinasync-awaitkotlin-coroutinessuspend

Tasks.await(task) shows Inappropriate blocking method call warning


I'm trying to perform sign out via Google in my code:

suspend fun signOut(context: Context): Boolean = with(Dispatchers.IO) {
    try {
        val signOutTask = GoogleSignIn.getClient(context, 
        getGoogleSignInOptionsBuilder()).signOut()
        Tasks.await(signOutTask)
        true
    } catch (e: ExecutionException) {
        false
    } catch (e: InterruptedException) {
        false
    }
}

The signOutTask is Task(Void) and I want it to return synchronously. But in the following line:

Tasks.await(signOutTask)

It shows Inappropriate blocking method call Appreciate your help!


Solution

  • When using Kotlin Coroutines with Google Play services' APIs, you should use the kotlinx-coroutines-play-services which does the correct work to convert the Task API into suspend APIs without blocking your thread:

    // In your dependencies block of your build.gradle
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.9"
    

    This lets you write your code as:

    suspend fun signOut(context: Context): Boolean = try {
        val signOutTask = GoogleSignIn.getClient(context,
             getGoogleSignInOptionsBuilder()).signOut()
        signOutTask.await()
        true
    } catch (e: Exception) {
        false
    }