Last active
January 3, 2023 09:04
-
-
Save jonatbergn/ed38ee1316f67acd543b0ea52b5f4e31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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