@@ -8,6 +8,8 @@ package kotlinx.coroutines.tasks
8
8
9
9
import com.google.android.gms.tasks.*
10
10
import kotlinx.coroutines.*
11
+ import java.lang.Runnable
12
+ import java.util.concurrent.Executor
11
13
import kotlin.coroutines.*
12
14
13
15
/* *
@@ -71,7 +73,8 @@ private fun <T> Task<T>.asDeferredImpl(cancellationTokenSource: CancellationToke
71
73
deferred.completeExceptionally(e)
72
74
}
73
75
} else {
74
- addOnCompleteListener {
76
+ // Run the callback directly to avoid unnecessarily scheduling on the main thread.
77
+ addOnCompleteListener(DirectExecutor ) {
75
78
val e = it.exception
76
79
if (e == null ) {
77
80
@Suppress(" UNCHECKED_CAST" )
@@ -114,7 +117,8 @@ public suspend fun <T> Task<T>.await(): T = awaitImpl(null)
114
117
* leads to an unspecified behaviour.
115
118
*/
116
119
@ExperimentalCoroutinesApi // Since 1.5.1, tentatively until 1.6.0
117
- public suspend fun <T > Task<T>.await (cancellationTokenSource : CancellationTokenSource ): T = awaitImpl(cancellationTokenSource)
120
+ public suspend fun <T > Task<T>.await (cancellationTokenSource : CancellationTokenSource ): T =
121
+ awaitImpl(cancellationTokenSource)
118
122
119
123
private suspend fun <T > Task<T>.awaitImpl (cancellationTokenSource : CancellationTokenSource ? ): T {
120
124
// fast path
@@ -133,7 +137,8 @@ private suspend fun <T> Task<T>.awaitImpl(cancellationTokenSource: CancellationT
133
137
}
134
138
135
139
return suspendCancellableCoroutine { cont ->
136
- addOnCompleteListener {
140
+ // Run the callback directly to avoid unnecessarily scheduling on the main thread.
141
+ addOnCompleteListener(DirectExecutor ) {
137
142
val e = it.exception
138
143
if (e == null ) {
139
144
@Suppress(" UNCHECKED_CAST" )
@@ -150,3 +155,12 @@ private suspend fun <T> Task<T>.awaitImpl(cancellationTokenSource: CancellationT
150
155
}
151
156
}
152
157
}
158
+
159
+ /* *
160
+ * An [Executor] that just directly executes the [Runnable].
161
+ */
162
+ private object DirectExecutor : Executor {
163
+ override fun execute (r : Runnable ) {
164
+ r.run ()
165
+ }
166
+ }
0 commit comments