Skip to content

Instantly share code, notes, and snippets.

@jonatbergn
Last active January 3, 2023 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonatbergn/ed38ee1316f67acd543b0ea52b5f4e31 to your computer and use it in GitHub Desktop.
Save jonatbergn/ed38ee1316f67acd543b0ea52b5f4e31 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.invoke
interface UseCase<State, Action> {
val actions: Flow<Action>
fun State.reduce(event: Action): State
}
interface Store<State> {
val state: StateFlow<State>
suspend fun <Event> UseCase<State, Event>.dispatch()
companion object Factory {
operator fun <T> CoroutineDispatcher.invoke(
state: T,
): Store<T> = StoreImpl(this, state)
}
}
private class StoreImpl<State>(
private val dispatcher: CoroutineDispatcher,
initialState: State,
) : Store<State> {
override val state: MutableStateFlow<State> = MutableStateFlow(initialState)
override suspend fun <Event> UseCase<State, Event>.dispatch() = dispatcher {
actions.collect { action -> state.update { state -> state.reduce(action) } }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment