https://kotlinlang.org logo
d

David Hart

01/20/2021, 1:28 PM
I'm trying to access
Thread.currentThread()
from a Kotlin Mobile Multiplatform project to check that I am in the main thread, but it doesn't seem accessible. Are my missing something? Is there another way?
a

Arkadii Ivanov

01/20/2021, 1:29 PM
There is no such a thing like Thread in common source set. But you can expect/actual.
k

Kris Wong

01/20/2021, 2:09 PM
Thread
is a Java API
e

edenman

01/20/2021, 7:48 PM
Copy code
expect fun isMainThread(): Boolean
actual fun isMainThread(): Boolean = Looper.getMainLooper() == Looper.myLooper()
(assuming you’ve got an android sourceset ofc)
d

David Hart

01/21/2021, 12:52 PM
Thanks for the answers!
m

Michal Klimczak

01/21/2021, 1:57 PM
If you're trying to do the same
actual
for iOS, it would be something like this
Copy code
import platform.Foundation.NSThread

actual fun currentThreadName() = "iOS thread ${NSThread.currentThread()} is main: ${NSThread.isMainThread()}"