<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stefan Serkhir on Medium]]></title>
        <description><![CDATA[Stories by Stefan Serkhir on Medium]]></description>
        <link>https://medium.com/@stefan.serkhir?source=rss-9ffe79fef115------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AyDjDHaBsB9HHOGN</url>
            <title>Stories by Stefan Serkhir on Medium</title>
            <link>https://medium.com/@stefan.serkhir?source=rss-9ffe79fef115------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:53:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefan.serkhir/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why is it so Convenient to Use the MVI Pattern in KMM]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/why-is-it-so-convenient-to-use-the-mvi-pattern-in-kmm-60563b18b061?source=rss-9ffe79fef115------2</link>
            <guid isPermaLink="false">https://medium.com/p/60563b18b061</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stefan Serkhir]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 11:46:54 GMT</pubDate>
            <atom:updated>2025-04-02T07:21:02.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Lmyln0lNP6COCT9Se8aFg.png" /></figure><p>Hi!</p><p>My name is Stefan Serkhir. I am a mobile developer at <a href="https://www.lonto.io/">Lonto</a>. I code for Android, iOS, and KMM (Kotlin Multiplatform Mobile) and teach courses.</p><p>The MVI approach at KMM is very convenient because:</p><ul><li>It is easy to share business logic across all platforms</li><li>You can extract separate functionality to the feature modules</li><li>MVI itself allows you to easily divide the screen into different states and change them depending on the user’s actions</li><li>It is very easy to put MVI on Jetpack Compose (Android) and SwiftUi (iOS)</li></ul><p>From this article you will know:</p><ul><li><strong>What is MVI</strong></li><li><strong>Pros and cons of MVI</strong></li><li><strong>What is KMM</strong></li><li><strong>MVI in KMM — practice</strong></li><li><em>How the project looks like from the Android side:</em></li><li>MainScreen</li><li>MainViewModel</li><li>MainStore</li><li>StoreFactory</li><li>Executor</li><li>Reducer</li><li><em>How the project looks like from the iOS side:</em></li><li>MainViewController</li><li>MainView</li><li><strong>Common code in Shared</strong></li><li><strong>Conclusion on the MVI in KMM</strong></li></ul><h3>What is MVI</h3><p><strong>MVI (Model-View-Intent)</strong> is an architectural pattern that is based on the idea of Unidirectional Data Flow and fits well with declarative UI frameworks such as Compose on Android and SwiftUI on iOS. MVI has several implementations: MVICore, MVIKotlin, Mosby, and many more. Some of them are multiplatform, that is they support KMP (Kotlin Multiplatform).</p><p>Historically, the roots of MVI stretch back to the Web, but today they are well used in Flutter (BLoC), for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38h9E4phTHfo981lmqIbOA.jpeg" /></figure><p>So we have the UI (our View) which is what users see. The essence of MVI is that users can interact with the View with special intents, and in our case it means the intention of users to take an action in the UI.</p><p>The intent is sent to the so-called black box, which processes it and returns the new state outside — it updates the model. Since the View is subscribed to this state, it receives it and renders a new one.</p><p>In the end, the UI has only one responsibility: to draw the current state. That is, our View contains no logic.</p><p>This black box is usually called the MVI-Feature, and the way it converts one state to another is called business logic.</p><h3>Pros and cons of MVI</h3><p><strong>Pros:</strong></p><ul><li>Integrates well with declarative UI frameworks such as Compose and SwiftUI</li><li>One single state which is drawn in the View</li><li>The state changes in one place. This makes it easy to debug, and you can’t see a non-consistent state on the screen. That is, we always see one particular state</li></ul><p><strong>Cons:</strong></p><ul><li>Boilerplate</li><li>You need to count the diff (difference, changes) of the state and redraw the changes only</li></ul><p>The state can be large on a complex screen, e.g. there can be 15 fields there. If you don’t count the diff, but redraw the whole screen every time the state is refreshed, the UI can be laggy… To do this, you need to count the state’s diff and redraw the changes only.</p><h3>What is KMM</h3><p><strong>KMM (Kotlin Multiplatform Mobile)</strong> is a subset of Kotlin Multiplatform.</p><p><strong>Kotlin Multiplatform</strong> is a technology that allows you to write code in Kotlin language for multiple platforms, or — in KMP terms — targets. Targets can be any popular platform, such as desktop: Linux, MacOS, Windows. If we talk about mobile operating systems, it’s Android and iOS. One recent update is that Aurora OS is now <a href="https://t.me/mobiledevnews/1341">supported</a>.</p><p>The Kotlin Multiplatform also supports the Web and smartwatch operating systems, such as watchOS.</p><p>In this article we will check out the KMM specifically. We will have two targets: Android and iOS. We will also focus on how MVI works with these two platforms.</p><p>In our project, we have two apps on iOS and Android with a native code. At the same time, these platforms depend on the shared code (also called the common code). The common code can contain business logic, basic stuff about dealing with networks or database, and complex calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b037lSt4XeASNRXhwpIAiA.jpeg" /></figure><p>There can also be platform-specific code in the common part. In the KMM case, these are iOS- and Android-specific APIs and classes. This is an advantage of KMM because it allows you to cover platform stuff with “interfaces” using the expect/actual mechanism. We discussed the implementation examples in the <a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">KMM Through the Eyes of an iOS Developer</a> article.</p><p>Let’s check out the project to see how it all works.</p><h3>MVI in KMM — practice</h3><p>Let’s look at MVI in practice. You can find an example of the project on <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample">GitHub</a>.</p><p>In this project, we have two apps: iOS and Android. They have one screen and a simple interface shown above.</p><p>In these apps, we can load information about the user: name, surname, date of birth, gender, and type of device. There is also one “Upload” button. If you tap it, you get the loading screen.</p><p>We may also have an error, and the app will notify us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlaMSNKQR_POrZlXyqWg_w.jpeg" /></figure><p>In this case we can reboot. And eventually we will be able to get our data.</p><p>The apps have no navigation, but only one screen and one MVI Feature. Under the hood, both iOS and Android apps use KMM and MVI (the implementation is <a href="https://arkivanov.github.io/MVIKotlin/">MVIKotlin</a>).</p><p>Now let’s look at the source code of this project. If you use Android Studio or IntelliJ IDEA, you should select the project view as Project to see all the source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-psuwStM872bf1J2Gyao9A.jpeg" /></figure><p>First of all, we want to see the folders in the root of the project: <em>androidApp</em>, <em>iosApp</em>, and <em>shared</em>. They have the app’s source code. The <em>androidApp</em> contains code for Android, the <em>iosApp</em> contains code for iOS, and the <em>shared</em> contains common code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwDl42DmYItXYeRi0YkjHQ.jpeg" /></figure><h3><strong>How the project looks like from the Android side</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejX0F1fs3hPlucumKBfetA.jpeg" /></figure><p>We’ve got one <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/androidApp/src/main/java/ru/kts/mobile/sample/android/MainActivity.kt">MainActivity</a> here. We should find the <em>private val viewModel by viewModel&lt;MainViewModel&gt;()</em> string and inject <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/presentation/MainViewModel.kt">ViewModel</a> there. And we collect the dependency graph in onCreate for simplicity:</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br><br>    initKoin {<br>        androidContext(applicationContext)<br>    }<br>}</pre><p>This is also where <em>setContent</em> is called, in which we describe our Views. In our case, the UI is written in Compose:</p><pre>setContent {<br>    val state by viewModel.state.collectAsState()<br><br>    MainScreen(<br>        state = state,<br>        onLoadClick = viewModel::load,<br>    )<br>}</pre><p>This call is similar to the usual setContent call, to which we pass the layout file. This is the usual extension that wraps Composable into a Compose view, a special View for Composable.</p><p>Inside <em>setContent</em> we do the following:</p><ol><li>We subscribe to the state that comes from the ViewModel by calling the <em>collectAsState</em> (but it is better to do it with <em>collectAsStateWithLifecycle</em>). This is important because we work with Compose, in which it is better to operate with the state, not just with Flow or RX entities.</li><li>We call the <em>MainScreen</em> Composable function. This is a usual Composable function, to which we pass the state and the load click event to our ViewModel. In this case, <em>viewModel::load</em> is a reference to the <em>load</em> method of ViewModel. We’ll discuss what’s in there a bit later.</li></ol><h4>MainScreen</h4><p>If we go to the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/androidApp/src/main/java/ru/kts/mobile/sample/android/ui/MainScreen.kt">MainScreen</a>, we see <em>when</em> with three branches:</p><pre>when {<br>    state.error -&gt; ErrorState(<br>        modifier = Modifier<br>            .align(Alignment.Center),<br>        onLoadClick = onLoadClick,<br>    )<br>    state.loading -&gt; CircularProgressIndicator(<br>        modifier = Modifier<br>            .align(Alignment.Center),<br>        color = buttonPrimaryActiveColor,<br>        strokeWidth = 3.dp,<br>    )<br>    userInfo != null -&gt; UserInfoDetails(<br>        modifier = Modifier<br>            .align(Alignment.Center),<br>        userInfo = userInfo,<br>        onLoadClick = onLoadClick,<br>    )<br>}</pre><p>Here we have three possible screen states:</p><ul><li><em>error</em>: the state with an error</li><li><em>loading</em>: loading state</li><li><em>userInfo</em>: the state of the screen when we have data and display it</li></ul><p>In larger projects we will have utilities written for this, so the code will look prettier. But we have a simplified example, so in this case it looks like this.</p><p>This is how the View draws the states: we have <em>when</em> with all possible states of the screen. And for each possible state of the screen a certain state is drawn. You can easily do this in Compose.</p><p>If you go back to MainActivity, you’ll see that the state comes from ViewModel. So let’s look at what we have there.</p><h4>MainViewModel</h4><p>In the constructor we have two private properties:</p><ul><li><em>store</em> is an MVI Feature</li><li><em>stateMapper</em> which maps the domain state to UiMainState</li></ul><pre>class MainViewModel(<br>    private val store: MainStore,<br>    private val stateMapper: Mapper&lt;MainStore.State, UiMainState&gt;,<br>)</pre><p>Ideally, the View should operate on the <em>UiState</em> and not on the domain state, since it should not know what is happening in our domain area.</p><p>In ViewModel we are interested in the public members of the class:</p><ul><li>The state property, which is declared with the <em>CStateFlow</em> type (we will tell about the first letter <em>C</em> in the name later), and the type of our state (<em>UIMainState</em>) is: <em>val state: CStateFlow&lt;UiMainState&gt;</em>. The state property represents the state to which the View is subscribed.</li><li>The <em>load: fun load() = store.accept(MainStore.Intent.Load)</em> method. This method proxies the event to the MVI Feature. In this case it is a loading event. To send this intent to the MVI Feature, we call the accept method and drop the desired intent there. In our case it is <em>MainStore.Intent.Load</em>.</li></ul><p>It is important to understand that the ViewModel should take the <em>UiState</em> from the Store. So in the <em>init</em> block we call the <em>bindAndStart</em>:</p><pre>init {<br>    bindAndStart {<br>        store.states.map(stateMapper::map) bindTo (::acceptState)<br>    }<br>    load()<br>}</pre><p>Inside the lambda of this method the following things happen:</p><ol><li>We take our <em>store</em> and the states it produces</li><li>We map them to the <em>UiState</em> using the <em>stateMapper</em>, which maps from the domain state to the <em>UiState</em></li><li>We bind these states to a method — to <em>acceptState</em> in our case</li><li>Inside the <em>acceptState</em> method, we put the UI state into the <em>mutableState</em> — a private field of the <em>MutableStateFlow&lt;UiMainState&gt;</em> type</li></ol><p>As a result, our state is obtained from the <em>mutableState</em>, which we first convert to the <em>CStateFlow</em> type by calling the <em>cStateFlow()</em> extension.</p><p>As we’ve noted earlier, we work with the <em>CStateFlow</em> type, not just the <em>StateFlow</em> type. The point is that this is not the Android’s ViewModel, but the KMM’s <a href="https://github.com/icerockdev/moko-mvvm">ViewModel</a>. It is located in the shared module, in the <em>commonMain</em>. And this ViewModel is shared between iOS and Android.</p><p>In Kotlin, interfaces support generics. And it is in Kotlin, where <em>StateFlow</em> is represented as an interface. You can read about the nuances of Kotlin and Swift interoperability in our <a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">KMM Through the Eyes of an iOS Developer </a>article.</p><p>That said, Swift also has interfaces. They are called protocols. But interfaces in Swift do not support generics, which is why we wrap our usual coroutine <em>StateFlow</em> in a utilitie called <em>CStateFlow</em>.</p><p>When the Kotlin code is compiled into Objective-C for iOS, you get the <em>CStateFlow</em> class there. And Swift classes can contain generics. So it’s just a utilitie for iOS compatibility. But it is essentially the same <em>StateFlow</em>.</p><p>We’ve described the ViewModel, and now we can go even deeper and get into our Store — specifically the MainStore declaration.</p><h4>MainStore</h4><p>This is a <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/api/MainStore.kt">standard interface</a> that inherits the Store interface.</p><p><strong>The Store interface</strong> is a base interface from the Kotlin MVI library. When we work with Kotlin MVI, it is inherited from the base Store and gives three generics to the base Store:</p><pre>interface MainStore : Store&lt;MainStore.Intent, MainStore.State, Nothing&gt;</pre><ul><li><em>MainStore.Intent</em> are the types of intents that can be sent to our feature — to the black box</li><li><em>MainStore.State</em> is the type of the state that the feature gives to the outside</li><li><em>Nothing</em> is a type of a label In our case we have no labels, so it’s Nothing</li></ul><p>MVI is good because it allows you to draw one particular state. In our case, labels are used for one-time events, like displaying a toast or a dialog, or performing navigation. That is, these are single-use things that should not be in the common state.</p><p>In our particular example, there are no labels because there is no navigation or a toast with an error.</p><p>Two entities are declared inside the interface itself:</p><p>1. Domain state:</p><pre>data class State internal constructor(<br>    val details: UserInfo? = null,<br>    val isLoading: Boolean = false,<br>    val isError: Boolean = false,<br>)</pre><p>It has three properties:</p><ul><li><em>details</em> — information about the user</li><li><em>isLoading</em> — shows whether the loading is in progress</li><li><em>isError</em> — shows if we’ve got an error</li></ul><p>In large projects, the <em>StringMessage</em> (for example) will be used instead of the <em>Boolean</em> type in <em>isError</em>. It’s because there are various errors in the business logic, and they are handled differently depending on the type of the error (roughly speaking, the type of the exception). And one <em>Boolean</em> is not enough for different types of errors.</p><p>2. Declaration of intents:</p><pre>sealed interface Intent {<br>    object Load : Intent<br>}</pre><p>Here we define the type of intents that can be sent to our feature.</p><p>In this case, we have only one intent: the <em>Load</em>. It is the loading intent. That said, there could have been another intent here, such as a refresh or text entry.</p><p>Usually intents are declared as <em>sealed</em> interfaces or <em>sealed</em> classes, because that way it is convenient to process them in the feature itself.</p><p>As a result, the <em>MainStore</em> interface is essentially a business logic API. There are no implementation details here. What we have is just a description of a state that our feature operates on. We also have descriptions of intents that this feature can accept.</p><p>The implementation of the business logic itself is in the <em>MainExecutor</em>, with an addition of <em>MainReducer</em> and <em>MainStoreFactory</em>. Let’s take a closer look at them.</p><p><strong>StoreFactory</strong></p><p>Since the feature is presented as an interface, we should create its implementation. To do this, we have <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/impl/MainStoreFactory.kt">StoreFactory</a> which allows you to create an instance of the MVI feature.</p><p>Usually all <em>StoreFactory</em> are very simple: they have one create type method only:</p><pre>fun create(): MainStore = object :<br>    MainStore,<br>    Store&lt;MainStore.Intent, MainStore.State, Nothing&gt; by storeFactory.create(<br>        name = MainStore::class.simpleName,<br>        initialState = MainStore.State(),<br>        bootstrapper = null,<br>        executorFactory = {<br>            MainExecutor(<br>                repository = repository,<br>            )<br>        },<br>        reducer = MainReducer(),<br>    ) {}</pre><p>The <em>create()</em> method creates an Object that inherits the <em>MainStore</em> interface and uses a kotlin delegate to create an implementation of our Store.</p><p>In addition to creation, usually Messages are described in <em>StoreFactory</em>. But you can also do it elsewhere: there are no limitations here. For example, you can describe the Store in one file, the intents in a second, and the state in a third. But it’s better to have it all coherent and kept in one place.</p><p>In our case, the <em>MainStoreFactory</em> describes the <em>sealed interface</em> <em>Message</em>:</p><pre>sealed interface Message {<br>    object SetLoading : Message<br>    data class SetUserInfo(val userInfo: UserInfo) : Message<br>    object SetError : Message<br>}</pre><p>This is an important point in the context of MVI, and we will also discuss it later.</p><p>Let’s recall that Store is created using the <em>StoreFactory</em> delegate. When we create this MVI feature, we can set some default behavior for it. For example, we want all of our MVI features to log the events that come into them, and the states they produce after those events. To do this, you need to define a base <em>StoreFactory</em>, which will contain this behavior.</p><p>If we go to the DI module (<a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/di/MainModule.kt">mainModule</a>), where <em>StoreFactory</em> is created, we see that it is created based on the <em>LoggingStoreFactory</em>. If you look at the name, you can see that the <em>LoggingStoreFactory</em> simply logs the events of the feature. Herewith the implementation of the logger can be anything, in our case it is <a href="https://github.com/AAkira/Napier">Napier</a>.</p><p>There are several ready-made implementations of the <em>StoreFactory</em> in the MVIKotlin library. You are free to choose the best implementation for your needs. There is also a default implementation that does nothing: it does not impose behavior.</p><p>Usually 100% of the time you use <a href="https://github.com/arkivanov/MVIKotlin/blob/master/mvikotlin-logging/src/commonMain/kotlin/com/arkivanov/mvikotlin/logging/store/LoggingStoreFactory.kt">LoggingStoreFactory</a> at a minimum. It allows you to log what happens inside the MVI feature. This helps with debugging an app, for example.</p><p>So, we’ve learnt what the <em>MainStoreFactory</em> is. Now let’s talk about the <em>Executor</em>, which contains most of the business logic.</p><h4>Executor</h4><p>A black box core that takes intents, does something with them, processes them, and outputs a new state. It contains the business logic of the app, passages through the repository to the network, databases, and calculations.</p><p>In our project, the <em>Executor</em> is called the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/impl/MainExecutor.kt">MainExecutor</a>. It inherits the base <em>Executor</em>.</p><p>The base <em>Executor</em> in this case simply wraps the methods from the library <em>Executor</em> in <em>scope.launch</em>:</p><pre>final override fun executeIntent(intent: Intent, getState: () -&gt; State) {<br>    scope.launch {<br>        suspendExecuteIntent(intent, getState)<br>    }<br>}<br><br>final override fun executeAction(action: Action, getState: () -&gt; State) {<br>    scope.launch {<br>        suspendExecuteAction(action, getState)<br>    }<br>}</pre><p>You need it so that you don’t have to wrap suspend-calls in <em>scope.launch</em> every time.</p><p>By default, <em>scope</em> in the <em>Executor</em> runs on the main thread because the state change must be in one thread. But coroutines let you easily do heavy or IO operations in other threads. It is also important to understand that the <em>dispose</em> of a feature cancels its <em>scope</em>, so we highly recommend to use cancelable suspend calls. Thus, because of the structured concurrency in Kotlin coroutines, all our operations within the scope will also be canceled. <a href="https://www.wwdcnotes.com/notes/wwdc21/10134/">This concept is conveniently implemented in iOS at the Swift language level.</a></p><p>We also have generics here that are given to the base <em>Executor</em>:</p><pre>internal abstract class BaseExecutor&lt;in Intent : Any, in Action : Any, in State : Any, Message : Any, Label : Any&gt;(<br>    mainContext: CoroutineContext = Dispatchers.Main,<br>) : CoroutineExecutor&lt;Intent, Action, State, Message, Label&gt;(mainContext = mainContext) {</pre><p>There are five generics here:</p><ul><li><em>Intent</em>: what the user sends to the feature</li><li><em>Action</em>: internal actions</li><li><em>State</em>: the state that the feature operates on</li><li><em>Message</em>: the result of processing the intent. Using it, the Reducer (we’ll talk about it later) will create a new state</li><li><em>Label</em>: a one-time event</li></ul><p>And what about that new gimmick — the <em>Action</em>? So, let’s say we have an app with a UI. The user can interact with this app, i.e. they can send intents to the feature. But sometimes you need to interact with a feature not from the outside, but from the inside.</p><p><strong>External interaction</strong> is when a user performs an action and an intent is sent.<br><strong>Internal Interaction</strong>. The example is when we need to stop network connection attempts when there’s no network. Instead, we need to go directly to the local database, so as not to waste resources and memory.</p><p>For such cases we have the <em>Action</em>. These are internal actions that we can send to our feature. They are used quite rarely, but they can be useful.</p><p>We also have the interesting suspendExecuteIntent method in the <em>MainExecutor</em>. It is defined from the base Executor. In this method, we accept the intents that the user sends to the black box.</p><p>The method signature contains the <em>intent</em> parameter and the <em>getState</em> lambda:</p><pre>override suspend fun suspendExecuteIntent(<br>    intent: MainStore.Intent,<br>    getState: () -&gt; MainStore.State,<br>) = when (intent) {<br>    is MainStore.Intent.Load -&gt; loadUserInfo()<br>}</pre><p><em>getState</em> is a lambda to be called. It will bring the current state back to us.</p><p>If we would have <em>state: MainStore.State</em> instead of <em>getState: () -&gt; MainStore</em>, then a link to a specific <em>State</em> object would come. In this case, we would not be able to get the actual state of the feature. That’s why it’s done as a lambda which allows you to get the named current state at the moment the lambda is called.</p><p>We keep going through the code and take <em>when</em> from the <em>Intent</em>. Since <em>Intent</em> is a <em>sealed</em> interface with one subclass, we can only have one branch — the <em>Load</em>. In it, we call the <em>loadUserInfo()</em> method.</p><p>In the next method we dispatch the <em>Message.SetLoading</em>:</p><pre>when (val response = repository.getUserInfo()) {<br>    is Response.Success -&gt; dispatch(MainStoreFactory.Message.SetUserInfo(response.data))<br>    is Response.Failed -&gt; dispatch(MainStoreFactory.Message.SetError)<br>}</pre><p>The <em>MainExecutor</em> contains the business logic, but it does not convert the current state to a new one. The <em>Reducer</em> entity is responsible for converting a state from the old to the new one after some business logic actions. We need it so that the <em>Executor</em> contains the business logic only. So everything the <em>Executor</em> does is dispatching the <em>Message.SetLoading</em>.</p><p>The <em>Reducer</em>, which we’ll talk about later, takes these <em>Messages</em>, takes the old state, and transforms it into the new one based on these <em>Messages</em>. And the feature will then release that state outside.</p><p>So, we actually say that we need to set the load state at the beginning of the <em>loadUserInfo</em> method. Then we go to the repository and get information about the user.</p><p>The <em>getUserInfo</em> method returns a utilitie in the form of the <em>Response</em>. This is a basic utilitie that has two subclasses: <em>Success</em> and <em>Failed</em>.</p><p>In real projects in production, the repository will not always return the data. It may return an exception: for example, an error may occur. In this case, the data types are usually wrapped in some kind of a utilitie at the repository. Here, it’s the <em>Response</em> utilitie.</p><p>The result is two situations: successful and unsuccessful data collection. It turns out that <em>when</em> has two branches.</p><p>If we’ve successfully collected the data, we dispatch it: <em>Message.SetUserInfo(response.data))</em>. This Message goes to the Reducer, where it converts the old state to the new one. And when we have an error, we put an error: <em>Message.SetError</em>.</p><p>Now let’s look at the Reducer.</p><h4>Reducer</h4><p>Ordinary class. It is inherited from the base library <em>Reducer</em> which overrides one method — <em>reduce</em>. Let’s check out the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/impl/MainReducer.kt">MainReducer</a>:</p><pre>internal class MainReducer : Reducer&lt;MainStore.State, MainStoreFactory.Message&gt; {<br><br>    override fun MainStore.State.reduce(<br>        msg: MainStoreFactory.Message,<br>    ) = when (msg) {<br>        is MainStoreFactory.Message.SetError -&gt; copy(<br>            isError = true,<br>            isLoading = false,<br>        )<br>        is MainStoreFactory.Message.SetUserInfo -&gt; copy(<br>            details = msg.userInfo,<br>            isLoading = false,<br>        )<br>        is MainStoreFactory.Message.SetLoading -&gt; copy(<br>            isLoading = true,<br>            isError = false,<br>        )<br>    }<br>}</pre><p>The essence of the <em>reduce</em> method is to convert the old state into a new one. This is done using the <em>copy</em> method, which is important because our state <strong>should be</strong> immutable. So we copy our old state and change certain properties in it.</p><p>The <em>Message</em> that comes to the <em>Reducer</em> has been declared as a <em>sealed</em> interface. So we can take <em>when</em> in the <em>reduce</em> method from this <em>Message</em>. As a result, we will have three branches in which the state will be transformed: <em>SetError</em>, <em>SetUserInfo</em>, and <em>SetLoading</em>.</p><p><strong>One-time events</strong></p><p>We mentioned the <em>Label</em> above that is used for one-time events. Let’s check out how it works and display a toast.</p><p>Let’s say we have a Store and we want to add a label to it. To do this we write the following code:</p><pre>sealed interface Label {<br>    object Toast : Label<br>}</pre><p>The label is called the <em>object Toast</em>. We need to put it in a generic. After that, we go to the <em>Executor</em>, where we pass the <em>Label</em> instead of <em>Nothing</em>:</p><pre>internal class MainExecutor(<br>    private val repository: Repository,<br>) : BaseExecutor&lt;MainStore.Intent, Nothing, MainStore.State, MainStoreFactory.Message, MainStore.Label&gt;() {</pre><p>In addition to the fact that we are already displaying the error state on the screen, we also want to display a toast. Let’s write it this way:</p><pre>when (val response = repository.getUserInfo()) {<br>    is Response.Success -&gt; dispatch(MainStoreFactory.Message.SetUserInfo(response.data))<br>    is Response.Failed -&gt; {<br>           publish(MainStore.Label.Toast) // “публикуем” наш label<br>           dispatch(MainStoreFactory.Message.SetError)                <br>}</pre><p>We go back to ViewModel and subscribe to the labels at the feature.</p><pre>init {<br>    bindAndStart {<br>        store.states.map(stateMapper::map) bindTo ::acceptState<br>        store.labels. bindTo ::acceptState // в метод acceptState будут приходить label-ы<br>    }<br>    load()<br>}</pre><p>We bind the labels to some method, the <em>acceptLabel</em> in our case:</p><pre>private fun acceptLabel(label: MainStore.Label)  {<br>}</pre><p>Now the labels will come into the <em>ViewModel</em>, and we can handle them in the <em>acceptLabel</em> method.</p><p>Summary of what was done:</p><ol><li>We declared the label in the Store as <em>sealed</em> interface/class</li><li>We went to the entity’s MVI and put the label instead of <em>Nothing</em> in the generic</li><li>We called the <em>publish</em> and passed the label there</li><li>In ViewModel, we took labels from the Store and bound them</li><li>In the UI, we subscribe to labels by <em>viewModel.labels.collect { … }</em> type</li><li>We display our toasts</li></ol><p>Since we describe MVI in the context of KMM, we will check out how it all looks in iOS.</p><h3>How the project looks like from the iOS side</h3><p>To check out an iOS project, you need to open the repository in Xcode. Xcode is a development environment in which iOS apps are written. Two languages are used there: Objective-C and Swift. Objective-C is like Java and Swift is like Kotlin. Our example is written in the second one.</p><p>In iOS , among the main entities we can distinguish:</p><ul><li><em>MainViewController</em>, an analog of a fragment from Android</li><li><em>MainAssembly</em> is where dependencies are added, including the ViewModel from the Koin</li><li><em>MainView</em> is the root view of our controller</li></ul><p>Swift doesn’t really know anything about Koin, so in order to get dependencies from KMM and then use them in Swift code, we need to use some iOS DI. In our case we use the <a href="https://github.com/Swinject/Swinject">Swinject</a> library to make things simpler.</p><p>Let’s take a brief look at the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/iosApp/App/Main/View/MainViewController.swift">MainViewController</a> and <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/iosApp/App/Main/View/MainView.swift">MainView</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJxK-yLWz_yaiZcMNRItPQ.jpeg" /></figure><h4>MainViewController</h4><p>The <strong>UIViewController in iOS</strong> is essentially analogous to fragments in Android. Let’s look at its code:</p><pre>final class MainViewController: UIViewController {<br>    <br>    private let viewModel: MainViewModel<br>    <br>    …<br>    <br>    private func bindUI() {<br>        <br>        viewModel.state.subscribe { [weak self] state in<br>            guard let state = state, let self = self else { return }<br>            <br>            if state.error {<br>                self.mainView.updateState(.error)<br>            } else if state.loading {<br>                self.mainView.updateState(.loading)<br>            } else if let details = state.userInfo {<br>                self.mainView.updateState(.normal(userInfo: details))<br>            }<br>        }<br>    }<br>        <br>    …<br>}</pre><p>This is where the ViewModel is transferred with the help of <a href="https://github.com/Swinject/Swinject">Swinject</a>. And in the <em>bindUI</em> method, just like in Android, we subscribe to the states that come from the ViewModel. Then we update the MainView according to the received state.</p><h4>MainView</h4><p>The root View on our screen. This is analogous to MainScreen from Android. In it we use cases to show this or that state.</p><h3>Common code in Shared</h3><p>Let’s recall that you can share the business logic, the data layer with KMM. But you can also use KMM to share even more code.</p><p>If we look in the res folder in androidApp, we can see that there are no other resources apart from styles. There are no strings, colors, or fonts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXHw34m_lPH2CIp1JKyt8Q.jpeg" /></figure><p>In our example, we have shared the resources between iOS and Android, so they are in the shared, in <em>CommonMain</em>. From the resources you can share colors, strings, images, fonts, and the community already has several ready-made solutions. We use <a href="https://github.com/Skeptick/libres">libres</a> and <a href="https://github.com/icerockdev/moko-resources">MOKO</a> libraries from IceRock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q95qT5hJYg86vk1GZXazow.jpeg" /></figure><p>The <strong>default</strong> resource structure in the KMM module</p><p>It is convenient when you work in a team. For example, if an iOS developer implements a feature, the Android developer won’t have to go to Figma, copy colors, strings, and images, download and convert them into Drawable XML files. In this case, the Android developer will only have to make up some UI, and all the logic and resources will be in the KMM.</p><p>This makes development cheaper, faster, and more enjoyable. Instead of having to breed these resources twice, they are created only once and are shared between platforms. Moreover, we essentially implement almost the same behavior on iOS and Android (except when it’s about platform peculiarities). And if there are bugs, they will most probably be common😁. But they will be fixed at once and in one place for both platforms.</p><p>The move to KMM changes almost nothing for the Android developer. We wrote about <a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">the iOS developers experience</a> earlier.</p><h3>Conclusion on the MVI in KMM</h3><p>We checked out MVI in KMM in practice and discovered how it looks in code from the Android and iOS side.</p><p>It helps to save time in the project, makes the development cheaper and more convenient.</p><p>Our project is small, but if you properly divide shared into modules, it can be easily scaled. The entry threshold for MVI is higher than for MVVM or MVP. For example, in the case of MVVM/MVP we would have only one additional entity — the ViewModel/Presenter. And with MVI we have three base entities, each with its own area of responsibility.</p><p>In my opinion, MVI is the most convenient architectural solution of the presentation layer, among those that the community has. It is because:</p><ul><li>The screen is always in one particular state</li><li>Easy to debug</li><li>The data goes in one direction, so it’s easy to track changes</li><li>Easy to reuse</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60563b18b061" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/why-is-it-so-convenient-to-use-the-mvi-pattern-in-kmm-60563b18b061">Why is it so Convenient to Use the MVI Pattern in KMM</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>