+++ title = 'MVI Architecture Helper' date = 2024-09-27T13:45:09+02:00 draft = true +++ Something smart to talk about this helper class {{< highlight kotlin >}} interface StateReceiver { suspend fun updateState(transform: suspend (STATE) -> STATE) suspend fun withState(block: suspend (STATE) -> Unit) } suspend inline fun StateReceiver.withType(crossinline block: suspend (TYPE) -> Unit) { withState { state -> if (state is TYPE) { block(state) } } } suspend inline fun StateReceiver.updateWithType(crossinline transform: suspend (TYPE) -> TYPE) { withType { state -> updateState { transform(state) } } } interface StateProvider { val state: StateFlow } interface IntentReceiver { fun handleIntent(intent: INTENT) } interface ActionProvider { val action: Flow } interface ActionReceiver { suspend fun sendAction(block: suspend () -> ACTION) } interface StateModule : StateReceiver, StateProvider interface IntentModule : IntentReceiver interface ActionModule : ActionReceiver, ActionProvider interface MVIViewModel : StateModule, IntentModule, ActionModule class MVIViewModelDelegate( initial: STATE ) : MVIViewModel { private val _state = MutableStateFlow(initial) override val state: StateFlow = _state.asStateFlow() private val _action = Channel() override val action: Flow = _action.receiveAsFlow() override suspend fun updateState(transform: suspend (STATE) -> STATE) { _state.update { transform(it) } } override suspend fun withState(block: suspend (STATE) -> Unit) { block(_state.value) } override suspend fun sendAction(block: suspend () -> ACTION) { _action.trySend(block()) } override fun handleIntent(intent: INTENT) { throw NotImplementedError() } } {{< / highlight >}}