android-ktx icon indicating copy to clipboard operation
android-ktx copied to clipboard

Looper.getMainLooper()-around extensions

Open romtsn opened this issue 7 years ago • 1 comments

I'm not sure that this is a good idea, cause we'd have a new instance of Handler each time this function is called, but would it worth to have something like this:

inline fun postOnUiThread(
    crossinline action: () -> Unit
): Runnable {
    val runnable = Runnable { action() }
    Handler(Looper.getMainLooper()).post(runnable)
    return runnable
}

And also the following boolean might be useful in some cases:

inline val isUiThread: Boolean
    get() = Looper.getMainLooper().thread == Thread.currentThread()

romtsn avatar May 10 '18 19:05 romtsn

Just as a reference to anko, they keep a reference of handler to avoid creating it each time. They will also avoid posting a runnable if you are already on the main thread

AllanWang avatar May 27 '18 22:05 AllanWang