Skip to content

Use DirectExecutor for Task.addOnCompleteListener #2992

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions integration/kotlinx-coroutines-play-services/src/Tasks.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ package kotlinx.coroutines.tasks

import com.google.android.gms.tasks.*
import kotlinx.coroutines.*
import java.lang.Runnable
import java.util.concurrent.Executor
import kotlin.coroutines.*

/**
Expand Down Expand Up @@ -71,7 +73,8 @@ private fun <T> Task<T>.asDeferredImpl(cancellationTokenSource: CancellationToke
deferred.completeExceptionally(e)
}
} else {
addOnCompleteListener {
// Run the callback directly to avoid unnecessarily scheduling on the main thread.
addOnCompleteListener(DirectExecutor) {
val e = it.exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
Expand Down Expand Up @@ -114,7 +117,8 @@ public suspend fun <T> Task<T>.await(): T = awaitImpl(null)
* leads to an unspecified behaviour.
*/
@ExperimentalCoroutinesApi // Since 1.5.1, tentatively until 1.6.0
public suspend fun <T> Task<T>.await(cancellationTokenSource: CancellationTokenSource): T = awaitImpl(cancellationTokenSource)
public suspend fun <T> Task<T>.await(cancellationTokenSource: CancellationTokenSource): T =
awaitImpl(cancellationTokenSource)

private suspend fun <T> Task<T>.awaitImpl(cancellationTokenSource: CancellationTokenSource?): T {
// fast path
Expand All @@ -133,7 +137,8 @@ private suspend fun <T> Task<T>.awaitImpl(cancellationTokenSource: CancellationT
}

return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
// Run the callback directly to avoid unnecessarily scheduling on the main thread.
addOnCompleteListener(DirectExecutor) {
val e = it.exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
Expand All @@ -150,3 +155,12 @@ private suspend fun <T> Task<T>.awaitImpl(cancellationTokenSource: CancellationT
}
}
}

/**
* An [Executor] that just directly executes the [Runnable].
*/
private object DirectExecutor : Executor {
override fun execute(r: Runnable) {
r.run()
}
}