-
-
Save arkivanov/77c41c3545fbe81358bd4627c3346506 to your computer and use it in GitHub Desktop.
MVIKotlin Store simplified
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 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 | |
} | |
} |
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 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