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

commonMain.co.touchlab.stately.isolate.IsoState.kt Maven / Gradle / Ivy

There is a newer version: 2.1.0
Show newest version
package co.touchlab.stately.isolate

import kotlin.native.concurrent.SharedImmutable

expect class StateHolder internal constructor(t: T, stateRunner: StateRunner) {
    val isDisposed: Boolean
    val myThread: Boolean
    val stateRunner: StateRunner
    val myState: T
    fun dispose()
}

open class IsolateState constructor(private val stateHolder: StateHolder) {
    constructor(stateRunner: StateRunner? = null, producer: () -> T) : this(createState(stateRunner, producer))

    val isDisposed: Boolean
        get() = stateHolder.isDisposed

    fun  fork(r: R): StateHolder = if (stateHolder.myThread) {
        StateHolder(r, stateHolder.stateRunner)
    } else {
        throw IllegalStateException("Must fork state from the state thread")
    }

    fun  access(block: (T) -> R): R {
        return if (stateHolder.myThread) {
            block(stateHolder.myState)
        } else {
            stateHolder.stateRunner.stateRun {
                block(stateHolder.myState)
            }
        }
    }

    fun dispose() = if (stateHolder.myThread) {
        stateHolder.dispose()
    } else {
        stateHolder.stateRunner.stateRun {
            stateHolder.dispose()
        }
    }
}

@SharedImmutable
internal val defaultStateRunner: BackgroundStateRunner = BackgroundStateRunner()

fun  createState(stateRunner: StateRunner?, producer: () -> T): StateHolder {
    val runner = stateRunner ?: defaultStateRunner
    return runner.stateRun { StateHolder(producer(), runner) }
}

/**
 * Hook to shutdown iso-state default runtime
 */
fun shutdownIsoRunner() {
    defaultStateRunner.stop()
}

internal sealed class RunResult
internal data class Ok(val result: T) : RunResult()
internal data class Thrown(val throwable: Throwable) : RunResult()




© 2015 - 2025 Weber Informatics LLC | Privacy Policy