commonMain.dev.stateholder.StateProvider.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of core Show documentation
Show all versions of core Show documentation
A simple library for managing state in Kotlin Multiplatform projects, using Kotlin Coroutines and `StateFlow`.
package dev.stateholder
/**
* A provider of a state for a [StateHolder].
*
* Sometimes we can have a simple state object that does not rely on outside sources. In that case
* you can just use [provideState], like so:
*
* ```
* val stateContainer = StateContainer.create(provideState(42))
* ```
*
* However sometimes we need to use a more complex state object that relies on outside sources. For
* that we might need to inject in some dependencies and create the state object.
*
* ```
* class MyRepo {
*
* fun getSomeData(): Int = 42
* }
*
* class MyStateProvider @Inject constructor(repo: MyRepo): StateProvider {
* override fun provide() = repo.getSomeData()
* }
*
* class MyModel @Inject constructor(stateProvider: MyStateProvider) : ViewModel() {
* private val container = stateContainer(stateProvider)
* }
* ```
*
* This provides a testable way to provide state for a [StateHolder].
*/
public fun interface StateProvider {
public fun provide(): State
}
/**
* Convenience function to create a simple [StateProvider] with a value.
*
* @param[State] The type of the state.
* @param[state] The state to provide.
* @return A [StateProvider] that provides the [state].
*/
public fun provideState(state: State): StateProvider = StateProvider { state }
/**
* Convenience function to create a lazily evaluated [StateProvider].
*
* @param[State] The type of the state.
* @param[block] The block that will be called to provide the state.
* @return A [StateProvider] that provides the state returned by [block].
*/
public fun provideState(
block: () -> State,
): StateProvider = StateProvider { block() }
/**
* Convenience function to create a [StateProvider] from any [T] value.
*
* @param[T] The type of the state.
* @return A [StateProvider] that provides the [T] value.
*/
public fun T.asStateProvider(): StateProvider = StateProvider { this }