Tasks.await(task) 显示不适当的阻塞方法调用警告

Udi*_*shi 1 android suspend async-await kotlin kotlin-coroutines

我正在尝试在我的代码中通过 Google 执行注销:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

signOutTask 是 Task(Void),我希望它同步返回。但在以下行中:

Tasks.await(signOutTask)
Run Code Online (Sandbox Code Playgroud)

它显示不适当的阻塞方法调用 感谢您的帮助!

ian*_*ake 6

将 Kotlin 协程与 Google Play 服务的 API 一起使用时,您应该使用kotlinx-coroutines-play-services正确的工作将TaskAPI 转换为suspendAPI,而不会阻塞您的线程:

// In your dependencies block of your build.gradle
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.9"
Run Code Online (Sandbox Code Playgroud)

这使您可以将代码编写为:

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