All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.arkivanov.mvikotlin.utils.internal.MainThreadAssert.kt Maven / Gradle / Ivy

There is a newer version: 3.3.0
Show newest version
package com.arkivanov.mvikotlin.utils.internal

var isAssertOnMainThreadEnabled: Boolean by atomic(true)

private val mainThreadIdRef = atomic(null)

fun assertOnMainThread() {
    if (isAssertOnMainThreadEnabled) {
        require(isMainThread()) {
            "Not on Main thread, current thread is: ${getCurrentThreadDescription()}"
        }
    }
}

internal expect fun getMainThreadId(): MainThreadId?

internal expect fun isMainThread(mainThreadId: MainThreadId): Boolean

internal expect fun getCurrentThreadDescription(): String

private fun isMainThread(): Boolean {
    val mainThreadId =
        mainThreadIdRef.initAndGet {
            val id: MainThreadId? = getMainThreadId()
            if (id == null) {
                logE("Main thread id is undefined, main thread assert is disabled")
            }
            MainThreadIdHolder(id)
        }

    return mainThreadId.id?.let(::isMainThread) ?: true
}

private inline fun  AtomicRef.initAndGet(init: () -> T): T {
    while (true) {
        var v: T? = value
        if (v != null) {
            return v
        }

        v = init()
        if (compareAndSet(null, v)) {
            return v
        }
    }
}

internal expect class MainThreadId

private class MainThreadIdHolder(val id: MainThreadId?)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy