Skip to content

Instantly share code, notes, and snippets.

@arkivanov
Last active October 30, 2021 23:26
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 arkivanov/77c41c3545fbe81358bd4627c3346506 to your computer and use it in GitHub Desktop.
Save arkivanov/77c41c3545fbe81358bd4627c3346506 to your computer and use it in GitHub Desktop.
MVIKotlin Store simplified
import com.arkivanov.mvikotlin.core.store.Store
import com.arkivanov.mvikotlin.extensions.coroutines.foo.MyStore.Intent
import com.arkivanov.mvikotlin.extensions.coroutines.foo.MyStore.Label
import com.arkivanov.mvikotlin.extensions.coroutines.foo.MyStore.State
interface MyStore : Store<Intent, State, Label> {
sealed interface Intent {
object Load : Intent
}
data class State(val value: String)
sealed interface Label {
object Loaded : Label
}
}
import com.arkivanov.mvikotlin.core.store.Reducer
import com.arkivanov.mvikotlin.core.store.SimpleBootstrapper
import com.arkivanov.mvikotlin.core.store.Store
import com.arkivanov.mvikotlin.core.store.StoreFactory
import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineExecutor
import com.arkivanov.mvikotlin.extensions.coroutines.foo.MyStore.Intent
import com.arkivanov.mvikotlin.extensions.coroutines.foo.MyStore.Label
import com.arkivanov.mvikotlin.extensions.coroutines.foo.MyStore.State
fun MyStore(storeFactory: StoreFactory): MyStore =
object : MyStore, Store<Intent, State, Label> by storeFactory.create(
initialState = State(value = ""),
bootstrapper = SimpleBootstrapper(Action.Init),
executorFactory = ::Executor,
reducer = ReducerImpl,
) {}
private sealed interface Action {
object Init : Action
}
private sealed interface Result {
data class Loaded(val value: String) : Result
}
private class Executor : CoroutineExecutor<Intent, Action, State, Result, Label>() {
override fun executeAction(action: Action, getState: () -> State) =
when (action) {
is Action.Init -> {
dispatch(Result.Loaded(value = "heh"))
publish(Label.Loaded)
}
}
override fun executeIntent(intent: Intent, getState: () -> State) =
when (intent) {
is Intent.Load -> {
dispatch(Result.Loaded(value = "mda"))
publish(Label.Loaded)
}
}
}
private object ReducerImpl : Reducer<State, Result> {
override fun State.reduce(result: Result): State =
when (result) {
is Result.Loaded -> copy(value = result.value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment