|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +package com.facebook.react.bridge |
| 9 | + |
| 10 | +import android.os.Handler |
| 11 | +import android.os.Looper |
| 12 | +import com.facebook.react.common.build.ReactBuildConfig |
| 13 | + |
| 14 | +/** Utility for interacting with the UI thread. */ |
| 15 | +public object UiThreadUtil { |
| 16 | + |
| 17 | + private val mainHandler: Handler by |
| 18 | + lazy(LazyThreadSafetyMode.NONE) { Handler(Looper.getMainLooper()) } |
| 19 | + |
| 20 | + /** |
| 21 | + * Returns the handler associated with the main (UI) thread. |
| 22 | + * |
| 23 | + * @return The handler for the main thread |
| 24 | + */ |
| 25 | + @JvmStatic public fun getUiThreadHandler(): Handler = mainHandler |
| 26 | + |
| 27 | + /** @return `true` if the current thread is the UI thread. */ |
| 28 | + @JvmStatic |
| 29 | + public fun isOnUiThread(): Boolean = Looper.getMainLooper().thread == Thread.currentThread() |
| 30 | + |
| 31 | + /** |
| 32 | + * Throws an [AssertionException] if the current thread is not the UI thread. This is a no-op in |
| 33 | + * production and is only meant to run in debug mode! If you need to check for incorrect-thread |
| 34 | + * issues in production, duplicate this code and call it elsewhere. |
| 35 | + */ |
| 36 | + @JvmStatic |
| 37 | + public fun assertOnUiThread() { |
| 38 | + if (ReactBuildConfig.DEBUG) { |
| 39 | + SoftAssertions.assertCondition(isOnUiThread(), "Expected to run on UI thread!") |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Throws an [AssertionException] if the current thread is the UI thread. This is a noop in |
| 45 | + * production, and is only meant to run in debug mode! If you need to check for incorrect-thread |
| 46 | + * issues in production, duplicate this code and call it elsewhere. |
| 47 | + */ |
| 48 | + @JvmStatic |
| 49 | + public fun assertNotOnUiThread() { |
| 50 | + if (ReactBuildConfig.DEBUG) { |
| 51 | + SoftAssertions.assertCondition(!isOnUiThread(), "Expected not to run on UI thread!") |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /** Runs the given [Runnable] on the UI thread. */ |
| 56 | + @JvmStatic |
| 57 | + public fun runOnUiThread(runnable: Runnable): Boolean = mainHandler.postDelayed(runnable, 0) |
| 58 | + |
| 59 | + /** Runs the given [Runnable] on the UI thread after the specified delay. */ |
| 60 | + @JvmStatic |
| 61 | + public fun runOnUiThread(runnable: Runnable, delayInMs: Long): Boolean = |
| 62 | + mainHandler.postDelayed(runnable, delayInMs) |
| 63 | + |
| 64 | + /** Removes the given [Runnable] on the UI thread. */ |
| 65 | + @JvmStatic |
| 66 | + public fun removeOnUiThread(runnable: Runnable) { |
| 67 | + mainHandler.removeCallbacks(runnable) |
| 68 | + } |
| 69 | +} |
0 commit comments