From 142a8ecfaa7f64bf921b55821bfc996383254b49 Mon Sep 17 00:00:00 2001 From: Pablo Baxter Date: Thu, 1 Sep 2022 21:33:38 -0700 Subject: [PATCH] Ensure `awaitFrame()` only awaits a single frame when used from the main thread --- ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt | 9 ++++++--- .../test/HandlerDispatcherTest.kt | 6 +++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt b/ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt index 5e33169dd1..91cd2abe98 100644 --- a/ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt +++ b/ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt @@ -190,11 +190,14 @@ public suspend fun awaitFrame(): Long { postFrameCallback(choreographer, cont) } } - // post into looper thread to figure it out return suspendCancellableCoroutine { cont -> - Dispatchers.Main.dispatch(EmptyCoroutineContext, Runnable { + if (Looper.myLooper() === Looper.getMainLooper()) { // Check if we are already in the main looper thread updateChoreographerAndPostFrameCallback(cont) - }) + } else { // post into looper thread to figure it out + Dispatchers.Main.dispatch(EmptyCoroutineContext, Runnable { + updateChoreographerAndPostFrameCallback(cont) + }) + } } } diff --git a/ui/kotlinx-coroutines-android/test/HandlerDispatcherTest.kt b/ui/kotlinx-coroutines-android/test/HandlerDispatcherTest.kt index fe97ae8d27..c016f35533 100644 --- a/ui/kotlinx-coroutines-android/test/HandlerDispatcherTest.kt +++ b/ui/kotlinx-coroutines-android/test/HandlerDispatcherTest.kt @@ -109,14 +109,14 @@ class HandlerDispatcherTest : TestBase() { launch(Dispatchers.Main, start = CoroutineStart.UNDISPATCHED) { expect(1) awaitFrame() - expect(5) + expect(3) } expect(2) // Run choreographer detection mainLooper.runOneTask() - expect(3) - mainLooper.scheduler.advanceBy(50, TimeUnit.MILLISECONDS) expect(4) + mainLooper.scheduler.advanceBy(50, TimeUnit.MILLISECONDS) + expect(5) mainLooper.scheduler.advanceBy(51, TimeUnit.MILLISECONDS) finish(6) }