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

commonMain.moe.tlaster.precompose.stateholder.StateHolder.kt Maven / Gradle / Ivy

Go to download

A third-party Jetbrains Compose library with ViewModel, LiveData and Navigation support.

There is a newer version: 1.7.0-alpha03
Show newest version
package moe.tlaster.precompose.stateholder

import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.compositionLocalOf

@OptIn(ExperimentalStdlibApi::class)
class StateHolder : AutoCloseable {
    private val _states = mutableMapOf()

    operator fun  set(key: String, value: T) {
        _states[key] = value
    }

    fun  getOrPut(key: String, defaultValue: () -> T): T {
        @Suppress("UNCHECKED_CAST")
        return _states.getOrPut(key) {
            defaultValue() as Any
        } as T
    }

    fun remove(key: String) {
        _states.remove(key)
    }

    operator fun  get(key: String): T? {
        @Suppress("UNCHECKED_CAST")
        return _states[key] as T?
    }

    override fun close() {
        for (value in _states.values) {
            if (value is AutoCloseable) {
                value.close()
            }
        }
        _states.clear()
    }

    // for testing
    internal fun contains(key: String): Boolean {
        return _states.containsKey(key)
    }
}

val LocalStateHolder = compositionLocalOf {
    error("No StateHolder provided")
}

/**
 * Returns the current [StateHolder] from composition or throws an [IllegalStateException]
 * if there is no [StateHolder] in provided.
 */
val currentLocalStateHolder: StateHolder
    @Composable
    @ReadOnlyComposable
    get() = LocalStateHolder.current




© 2015 - 2024 Weber Informatics LLC | Privacy Policy