commonMain.co.touchlab.stately.isolate.IsoState.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of stately-isolate-js Show documentation
Show all versions of stately-isolate-js Show documentation
Multithreaded Kotlin Multiplatform Utilities
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