Skip to content

Commit 95892c2

Browse files
pablobaxterqwwdfsad
authored andcommitted
Ensure awaitFrame() only awaits a single frame when used from the main thread
1 parent 7d8e275 commit 95892c2

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt

+6-3
Original file line numberDiff line numberDiff line change
@@ -190,11 +190,14 @@ public suspend fun awaitFrame(): Long {
190190
postFrameCallback(choreographer, cont)
191191
}
192192
}
193-
// post into looper thread to figure it out
194193
return suspendCancellableCoroutine { cont ->
195-
Dispatchers.Main.dispatch(EmptyCoroutineContext, Runnable {
194+
if (Looper.myLooper() === Looper.getMainLooper()) { // Check if we are already in the main looper thread
196195
updateChoreographerAndPostFrameCallback(cont)
197-
})
196+
} else { // post into looper thread to figure it out
197+
Dispatchers.Main.dispatch(EmptyCoroutineContext, Runnable {
198+
updateChoreographerAndPostFrameCallback(cont)
199+
})
200+
}
198201
}
199202
}
200203

ui/kotlinx-coroutines-android/test/HandlerDispatcherTest.kt

+3-3
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,14 @@ class HandlerDispatcherTest : TestBase() {
109109
launch(Dispatchers.Main, start = CoroutineStart.UNDISPATCHED) {
110110
expect(1)
111111
awaitFrame()
112-
expect(5)
112+
expect(3)
113113
}
114114
expect(2)
115115
// Run choreographer detection
116116
mainLooper.runOneTask()
117-
expect(3)
118-
mainLooper.scheduler.advanceBy(50, TimeUnit.MILLISECONDS)
119117
expect(4)
118+
mainLooper.scheduler.advanceBy(50, TimeUnit.MILLISECONDS)
119+
expect(5)
120120
mainLooper.scheduler.advanceBy(51, TimeUnit.MILLISECONDS)
121121
finish(6)
122122
}

0 commit comments

Comments
 (0)