<?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"><channel><title><![CDATA[Michal Konkel Developer Blog]]></title><description><![CDATA[Michal Konkel Developer Blog]]></description><link>https://michalkonkel.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 15 Nov 2026 21:24:32 GMT</lastBuildDate><atom:link href="https://michalkonkel.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Benefits of Using Compose Multiplatform for Mobile Applications]]></title><description><![CDATA[Explore the advantages of using Compose Multiplatform for mobile apps, including cost-effectiveness, ease of transition, and unified business logic]]></description><link>https://michalkonkel.dev/benefits-of-using-compose-multiplatform-for-mobile-applications</link><guid isPermaLink="true">https://michalkonkel.dev/benefits-of-using-compose-multiplatform-for-mobile-applications</guid><category><![CDATA[andorid]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[compose multiplatform]]></category><category><![CDATA[iOS]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[fintech]]></category><category><![CDATA[banking]]></category><category><![CDATA[Jetbrains]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Tue, 01 Apr 2025 08:52:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743496551743/b172356c-f53c-413d-808c-090a7f8b94d4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-ia"> </h2>
<p><strong>Compose Multiplatform – The Future of Mobile Apps or Just Another Experiment?</strong></p>
<p>Over the years, many cross-platform solutions have emerged, trying to bridge the gap between costly native app development and the more affordable method of creating two applications from one codebase. I’ve worked with several of them - Cordova, Xamarin, React Native, and more recently, Flutter. While each has its benefits, they all seem to miss something important.</p>
<p>One of the main drawbacks that has discouraged me from using these technologies for enterprise projects is the lack of an easy exit strategy. If you choose to move away from something like React Native (due to limitation or a pivot) to native development, the switch can be very costly. You have to change your company’s skill set, hire new developers, or outsource teams, and the whole development process needs to start over from the beginning.</p>
<p>After months or even years of work, you might find yourself with nothing and have to rebuild your project from scratch. That's probably why some Cordova-based projects still exist, even though maintaining them is very difficult. Similarly, there are .NET developers who need to support and expand Xamarin applications, even though Microsoft has moved on to a different approach.</p>
<h3 id="heading-so-how-is-compose-multiplatform-different-why-isnt-it-doomed-to-fail">So, How Is Compose Multiplatform Different? Why Isn’t It Doomed to Fail?</h3>
<p>Because it’s <strong>natively integrated</strong> from an Android development perspective. Regardless of whether you use Compose Multiplatform (CMP) or “pure” Android development, you’re still writing in <strong>Kotlin</strong> - Google’s officially recommended language for Android apps.</p>
<p>Furthermore, <strong>Jetpack Compose</strong> is the designated UI framework for Android, meaning that whether you go with native Android or CMP, your screens are built in the same way. From a pragmatic perspective, <strong>there’s no difference.</strong></p>
<p>With CMP, <strong>Android remains fully native</strong>, while iOS becomes the <code>hybrid</code> part. This is a completely different approach compared to other cross-platform solutions. With Flutter or React Native, <strong>both platforms</strong> are developed outside their “natural environments”, using a non-native language for each. This inevitably leads to compromises and imperfections.</p>
<h3 id="heading-the-business-perspective-why-does-it-matter">The Business Perspective – Why Does It Matter?</h3>
<p>The most crucial factor in modern product development is <strong>validation with real users</strong>. The key question is: <strong>How quickly can we deliver a working solution and determine if our app even makes sense?</strong></p>
<p>A rapid <strong>MVP (Minimum Viable Product)</strong> can be the deciding factor in whether your project is a hit or a complete failure. With CMP, we get an <strong>almost fully native Android app</strong>, and from the same codebase, we generate an <strong>iOS app</strong>.</p>
<p>This strategic approach <strong>significantly reduces the development time</strong> required to build applications and speeds up the <strong>time to market</strong>. By doing so, we can reach our users more quickly, enabling us to gather valuable feedback and insights sooner. This feedback is essential for iterative improvements and ensuring that the app aligns with user expectations and demands. Ultimately, this accelerated process enhances our ability to adapt and refine our product, increasing the likelihood of success in a competitive market</p>
<h3 id="heading-the-best-part-theres-no-lock-in">The Best Part? There’s No Lock-In</h3>
<p>If at any point you decide to move away from CMP and switch to fully native development, you already have a <strong>complete Android app</strong> ready to go. This means there's no need for any rewrites on the Android side, which can save a significant amount of time and resources. You would simply stop generating the iOS version through CMP and instead, focus on rewriting it natively using <strong>Swift and SwiftUI</strong>. This transition allows you to take full advantage of the native features and performance optimizations available on iOS.</p>
<p>Alternatively, you might find that CMP perfectly meets all your needs and expectations, proving to be an ideal solution for your business requirements. With CMP, development remains <strong>faster and more cost-effective</strong> compared to traditional mobile app development methods..</p>
<h3 id="heading-native-ui-when-it-matters">Native UI When It Matters</h3>
<p>CMP does not prevent you from using <strong>native UI components</strong> (especially for iOS) when needed. By applying the <strong>Pareto principle (80/20 rule)</strong>, which suggests that 20% of an app's features provide 80% of its value, you can strategically combine hybrid and native development approaches:</p>
<ul>
<li><p>If your app’s <strong>dashboard needs to be visually stunning and highly interactive</strong>, consider building it natively. This allows you to leverage the full power of native capabilities to create an engaging and smooth user experience that can impress your users and meet their high expectations.</p>
</li>
<li><p>On the other hand, if your <strong>settings screen</strong> is just a straightforward list that users infrequently visit, you can build it once using CMP. This approach saves time and resources, as CMP allows you to efficiently create and maintain such simple components without the need for extensive native development. This way, you can focus your efforts on the parts of the app that truly require the native touch, ensuring that your development process remains efficient and cost-effective.</p>
</li>
</ul>
<h3 id="heading-unified-business-logic-a-key-advantage">Unified Business Logic – A Key Advantage</h3>
<p>With CMP, you have the advantage of <strong>centralizing your business logic</strong> in a single location. This means that when you identify and fix a bug in one section of your code, the fix is automatically applied to both Android and iOS platforms at the same time. This unified approach not only ensures that your app behaves consistently across different devices and operating systems, but it also significantly reduces the time and effort required for maintenance. By having a single codebase to manage, developers can streamline updates and improvements, leading to a more efficient development process.</p>
<h3 id="heading-want-to-learn-more">Want to Learn More?</h3>
<p>Let me know your thoughts! If you're curious and want to chat, we can discuss my experience in <strong>launching the largest Kotlin Multiplatform-based banking app in Poland.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Compose Multiplatform Navigation Solutions - JetpackCompose Navigation]]></title><description><![CDATA[Explore Jetpack Compose for multiplatform projects to enhance code sharing and cross-platform consistency with modern UI toolkit capabilities]]></description><link>https://michalkonkel.dev/compose-multiplatform-navigation-solutions-jetpackcompose-navigation</link><guid isPermaLink="true">https://michalkonkel.dev/compose-multiplatform-navigation-solutions-jetpackcompose-navigation</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[navigation]]></category><category><![CDATA[mobile app development]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[mobile app architecture]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[Jetpack Compose]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Mon, 04 Nov 2024 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730840545342/c81053de-54a9-48d9-8b2a-7e2ec45fcc91.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the upcoming posts, I will thoroughly explore several popular navigation libraries that are essential for effective app development. These libraries play a crucial role in managing app navigation, ensuring a smooth and intuitive user experience. Navigation is a key aspect of any app, as it helps users move seamlessly between different screens and features.</p>
<p>In this project, I will showcase JetpackCompose as the primary tool for app navigation. JetpackCompose is a modern toolkit for building native UI, and it offers a powerful and flexible way to handle navigation within your app. By using JetpackCompose, developers can create a more cohesive and responsive user interface.</p>
<p>Since the navigation is being transitioned from Android to a multiplatform project, it is important to explore how JetpackCompose can be utilized in this new context. This transition opens up new possibilities for code sharing and consistency across different platforms. We definitely should give it a try to see how it performs and what benefits it brings to the table. For more information on this topic, you can check out this official guide on <a target="_blank" href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-navigation-routing.html">Compose Navigation</a>.</p>
<p>Assumptions:</p>
<ul>
<li><p>Application should allow us to navigate from one screen to another.</p>
</li>
<li><p>Application should allow to pass some parameters from first to second screen.</p>
</li>
<li><p>Application should handle the screen rotation without loosing data.</p>
</li>
<li><p>Application should handle the Tab Navigation.</p>
</li>
<li><p>Application should handle the async operations with coroutines.</p>
</li>
</ul>
<blockquote>
<p>The project is available in the <a target="_blank" href="https://github.com/mkonkel/JetpackComposeNavigation">GitHub</a> repository.</p>
</blockquote>
<hr />
<h1 id="heading-dependencies">Dependencies</h1>
<p>Base project setup, as always, is made with <a target="_blank" href="https://kmp.jetbrains.com/">Kotlin Multiplatform Wizard</a>. We also need to add some navigation-compose dependencies, as it is the core thing that we would like to examine. According to the <a target="_blank" href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-navigation-routing.html#sample-project">documentation</a>, we should use <code>navigation</code> in version <code>2.8.0-alpha08</code> and <code>kotlinx.serialization</code>.</p>
<blockquote>
<p>Good news are that the new update of compose multiplatform is available. The version <code>1.7.0-alpha01</code>that brings the <code>Safe Args</code>!</p>
</blockquote>
<pre><code class="lang-kotlin">[versions]
compose-plugin = <span class="hljs-string">"1.7.0-alpha01"</span>
navigation-compose = <span class="hljs-string">"2.8.0-alpha08"</span>
serialization = <span class="hljs-string">"1.6.3"</span>

[libraries]
navigation-compose = { module = <span class="hljs-string">"org.jetbrains.androidx.navigation:navigation-compose"</span>, version.ref = <span class="hljs-string">"navigation-compose"</span> }
serialization-json = { module = <span class="hljs-string">"org.jetbrains.kotlinx:kotlinx-serialization-json"</span>, version.ref = <span class="hljs-string">"serialization"</span> }

[plugins]
jetbrainsCompose = { id = <span class="hljs-string">"org.jetbrains.compose"</span>, version.ref = <span class="hljs-string">"compose-plugin"</span> }
kotlinSerialization = { id = <span class="hljs-string">"org.jetbrains.kotlin.plugin.serialization"</span>, version.ref = <span class="hljs-string">"kotlin"</span> }
</code></pre>
<p>Freshly added dependencies needs to be synced with the project and added to the <strong><em>build.gradle.kts</em></strong></p>
<pre><code class="lang-kotlin">plugins {
    alias(libs.plugins.kotlinSerialization)
}

sourceSets {
    commonMain.dependencies {
        ...
        implementation(libs.navigation.compose)
        implementation(libs.serialization.json)
    }
}
</code></pre>
<h1 id="heading-navigation">Navigation</h1>
<p>Getting started with navigation in Compose Multiplatform can seem daunting at first, but it's quite straightforward once you understand the basics. The key question is: how does the navigation system know where to go? The answer lies in the concept of destinations. Each destination has a unique identifier that specifies the current screen to be displayed.</p>
<p>In most cases, a destination will be a composable function. This function represents the UI that will be shown on the screen. By assigning a unique ID to each composable function, the navigation system can easily determine which screen to display based on user actions or other triggers.</p>
<blockquote>
<p>Note:</p>
<p>In previous versions of navigation the route was defined as a string (you can think of it as the <code>URL</code> address). But now we have more robust approach where we can pass an <code>Object/Class/KClass</code> as a destination as log as they are serializable.</p>
</blockquote>
<h2 id="heading-linear-navigation">Linear Navigation</h2>
<p>Let's start with the <code>Screen</code> sealed class that will hold the destinations.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Screen</span> </span>{
    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> First : Screen()

    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Second : Screen()
}
</code></pre>
<p>Now we can create the <code>Navigation</code> composable function, which will hold the <code>NavHost</code> and <code>navigationController</code>. The <code>NavHost</code> acts as the container responsible for displaying the current destination. It ensures that the appropriate composable function is shown based on the navigation state. The <code>navigationController</code> is the object that manages the navigation between destinations, allowing us to move from one screen to another seamlessly.</p>
<p>The <code>NavGraph</code> is another crucial component in this setup. It maps composable destinations to their respective routes, defining the navigation paths within the app. By setting up the <code>NavGraph</code>, we establish the relationships between different screens and specify how users can navigate through them.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Navigation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> navController = rememberNavController()

    NavHost(
        navController = navController,
        startDestination = Screen.First,
    ) {
        composable&lt;Screen.First&gt; {
            FirstScreen(navController)
        }

        composable&lt;Screen.Second&gt; {
            SecondScreen(navController)
        }
    }
}
</code></pre>
<p>With the navigation framework built, we should implement some screens. The <code>First</code> screen will be really simple, with a single button that will navigate to the <code>Second</code> screen. The <code>Second</code> screen will also be simple, with a button that will navigate back.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreen</span><span class="hljs-params">()</span></span> {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(<span class="hljs-string">"First screen"</span>)
        Button(onClick = { <span class="hljs-comment">/*TODO navigate to the second screen*/</span> }) {
            Text(<span class="hljs-string">"Second Screen"</span>)
        }
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">SecondScreen</span><span class="hljs-params">()</span></span> {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(<span class="hljs-string">"Second screen"</span>)
        Spacer(modifier = Modifier.height(<span class="hljs-number">16</span>.dp))
        Button(onClick = { <span class="hljs-comment">/*TODO navigate back to first screen*/</span> }) {
            Text(<span class="hljs-string">"Go Back"</span>)
        }
    }
}
</code></pre>
<p>Now, let's fill in the gaps in the <code>Navigation()</code> function with the screens we created. We left some TODOs in the screens that need to be addressed. To navigate between screens, we need to pass the <code>navController</code> as an input to our composable functions. For navigation, we will use the <code>navigate()</code> method to move to the next screen and the <code>popBackStack()</code>method to return to the previous screen.</p>
<pre><code class="lang-kotlin">Button(onClick = { navController.navigate(Screen.Second) }) { Text(<span class="hljs-string">"Second Screen"</span>) }
</code></pre>
<pre><code class="lang-kotlin">Button(onClick = { navController.navigate(Screen.Second) }) { Text(<span class="hljs-string">"Second Screen"</span>) }
</code></pre>
<p>With the initial setup complete, the next step is to integrate the <code>Navigation()</code> function into the main entry point of the application. For Android, this entry point is typically the <code>MainActivity.kt</code> file, while for iOS, it is the <code>MainViewController.kt</code> file. In these files, you will initialize the navigation controller and set up the navigation graph to manage the different screens of your app.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">ComponentActivity</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)

        setContent {
            Navigation()
        }
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">MainViewController</span><span class="hljs-params">()</span></span> = ComposeUIViewController { Navigation() }
</code></pre>
<p>After running the application we should see the <code>First</code> scree with a button that navigates to the <code>Second</code> screen and a button that navigates back to the <code>First</code> screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721995990192/b207b5fd-93eb-436c-8fc1-0551e14b0f78.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-passing-parameters">Passing parameters</h2>
<blockquote>
<p>Note:</p>
<p>Now with Safe Args passing values is easy, but with the previous release passing arguments was tricky. Since the route looks like the URL address required arguments should be passed as a <code>path</code> in route and the optional as <code>query</code></p>
</blockquote>
<p>With the <code>Safe Args</code> we can pass parameters as the part of the destination object which is easy and convenient, there are two types of arguments <strong>required</strong> and <strong>optional.</strong></p>
<h3 id="heading-required-arguments">Required Arguments</h3>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Screen</span> </span>{
    ...
    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Third</span></span>(<span class="hljs-keyword">val</span> greeting: String) : Screen()
}
</code></pre>
<p>Now we need to create the <code>ThirdScreen</code> composable function that will accept the <code>greetings</code> parameter and provide a way to pass the arguments. Since the <code>composable&lt;T&gt;()</code> is a typed function where <code>T</code> is the route from a <code>KClass</code> for the destination, we can use the <code>.toRoute&lt;T&gt;()</code> function. This extension function returns the route as an object of type <code>T</code>. From now on, we can extract the arguments from the passed class. As we know what type of class it is, we also know what type the arguments are.</p>
<p>Since we know that the passing argument is a <code>String</code>, we can extract it from the route and pass it to the <code>ThirdScreen</code> composable.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Navigation</span><span class="hljs-params">()</span></span> {
    NavHost(...) {
        ...
        composable&lt;Screen.Third&gt; {
            <span class="hljs-keyword">val</span> args = it.toRoute&lt;Screen.Third&gt;()

            ThirdScreen(
                navController = navController,
                greetings = args.greeting
            )
        }
    }
}
</code></pre>
<p>Let's modify the <code>First</code> screen to navigate to the <code>Third</code> screen with the greeting parameter as an argument of the data class.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    ...
    Button(
        onClick = {
            <span class="hljs-keyword">val</span> greetings = <span class="hljs-string">"Hello from First Screen"</span>
            navController.navigate(Screen.Third(greetings))
        }
    ) {
        Text(<span class="hljs-string">"Third Screen"</span>)
    }
}
</code></pre>
<p>The <code>Third</code> screen should be built in the same way as the <code>Second</code> screen, but with the appropriate parameters passed.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">ThirdScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>, greetings: <span class="hljs-type">String</span>)</span></span> {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(<span class="hljs-string">"Third screen"</span>)
        Spacer(modifier = Modifier.height(<span class="hljs-number">16</span>.dp))
        Text(<span class="hljs-string">"Greetings: <span class="hljs-variable">$greetings</span>"</span>)
        Spacer(modifier = Modifier.height(<span class="hljs-number">16</span>.dp))
        Button(onClick = { navController.popBackStack() }) {
            Text(<span class="hljs-string">"Go Back"</span>)
        }
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721996603228/afa69c26-ab9b-4834-9d54-ec114e56763d.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-optional-arguments">Optional Arguments</h3>
<p>For optional arguments we will follow same idea as with required arguments. Let's create the <code>Fourth</code> screen that will have two optional arguments <code>name</code> and <code>surname</code>.</p>
<details><summary>Without the safe args</summary><div data-type="detailsContent">With the <code>Safe Args</code>, it's easy to pass optional arguments. In previous versions, we needed to use <code>query</code> parameters where arguments should be passed in the <code>route</code> and preceded by a <code>?</code> character following the pattern <code>?key=value</code>, and if you want to pass multiple optional parameters, they have to be separated with the <code>&amp;</code> character <code>?key1=value1&amp;key2=value2</code>. Also, the optional parameters have to be provided with a default value.</div></details>

<p>With the <code>Safe Args</code>, it's easy to pass optional arguments. In previous versions, we needed to use <code>query</code> parameters where arguments should be passed in the <code>route</code> and preceded by a <code>?</code> character following the pattern <code>?key=value</code>, and if you want to pass multiple optional parameters, they have to be separated with the <code>&amp;</code> character <code>?key1=value1&amp;key2=value2</code>. Also, the optional parameters have to be provided with a default value.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Fourth</span></span>(<span class="hljs-keyword">val</span> name: String, <span class="hljs-keyword">val</span> surname: String? = <span class="hljs-literal">null</span>) : Screen()
</code></pre>
<p>Now we need to create the <code>Fourth</code> screen composable function that will accept the <code>name</code> and <code>surname</code> parameters.</p>
<pre><code class="lang-kotlin">composable&lt;Screen.Fourth&gt; {
    <span class="hljs-keyword">val</span> args = it.toRoute&lt;Screen.Fourth&gt;()

    FourthScreen(
        navController = navController,
        name = args.name,
        surname = args.surname
    )
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FourthScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>, name: <span class="hljs-type">String</span>, surname: <span class="hljs-type">String</span>?)</span></span> {
    ...
}
</code></pre>
<p>Navigation is as simple as it can possibly be:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    Button(onClick = { navController.navigate(Screen.Fourth(name = <span class="hljs-string">"John"</span>, surname = <span class="hljs-string">"Doe"</span>)) }) {
        Text(<span class="hljs-string">"John Doe Screen"</span>)
    }

    Button(onClick = { navController.navigate(Screen.Fourth(name = <span class="hljs-string">"Michael"</span>)) }) {
        Text(<span class="hljs-string">"Michael Screen"</span>)
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721996846781/e0d0171e-3736-4e36-b1b6-e5afbc6933a1.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-nested-navigation">Nested Navigation</h2>
<p>In the case of complex applications, splitting navigation into smaller parts is a good idea. Currently, we have one <code>NavHost</code> with all screens originating from the same place. We can divide the navigation into smaller parts that will be encapsulated according to their purpose. Let's create a <code>Fifth</code> and <code>Sixth</code> screen that will be separate from the main navigation and will be accessible only from the <code>Third</code> screen. The graph for such screens will look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721997124488/dff8ebe2-f1c1-46ee-98ef-40d69823bb89.png" alt class="image--center mx-auto" /></p>
<p>With such structured navigation, we can easily manage the navigation and the screens. We can create a <code>NestedNavigation</code> composable function that will hold the <code>NavHost</code> and <code>navigationController</code> for the nested navigation. When we close the <code>Third</code> screen, navigation will remove all its children from the backstack, and they won't be accessible anymore. It's a great tool for structuring processes in the application—when a process is finished (for example, a signup, a payment, or a tutorial).</p>
<blockquote>
<p>If you read my post about navigation <a target="_blank" href="https://hashnode.com/post/clypbla0r000909l4gov25akn">Decompose</a> you can, you will see similarities in the approach. In Decompose, every component can have its own stack and manage it.</p>
</blockquote>
<p>Adding the nested navigation graph is accomplished by using the <code>navigation()</code> function within the <code>NavHost</code> composable. The <code>navigation()</code> function requires two key parameters: <code>startDestination</code> and <code>route</code>. The <code>route</code> serves as a unique identifier for the nested navigation graph, ensuring it is distinct from other navigation graphs within the application. This identifier can be a unique name or an object.</p>
<p>The <code>startDestination</code> parameter specifies the initial screen that will be displayed when the nested navigation graph is activated. This is the entry point for the nested navigation, guiding users to the first screen they will interact with in this part of the app.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Route</span> </span>{
    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Root : Route()

    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Main : Route()

    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Nested : Route()
}

<span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Navigation</span><span class="hljs-params">()</span></span> {

    NavHost(
        navController = navController,
        startDestination = Screen.First,
        route = Route.Root::<span class="hljs-class"><span class="hljs-keyword">class</span></span>
    ) {
        ...
        navigation(
            startDestination = Screen.Fifth,
            route = Route.Nested::<span class="hljs-class"><span class="hljs-keyword">class</span></span>
        ) {
            composable&lt;Screen.Fifth&gt; {
                FifthScreen(navController)
            }

            composable&lt;Screen.Sixth&gt; {
                SixthScreen(navController)
            }

            composable&lt;Screen.Seventh&gt; {
                SeventhScreen(navController)
            }
        }
    }
}
</code></pre>
<p>To clarify the navigation, we can split the <code>Navigation()</code> function into separate components. The first will handle the <code>main</code> graph, and the second will handle the <code>nested</code> graph. To do this, we need to create extension functions for <code>NavGraphBuilder</code> that will hold specific screens, resulting in the following graph changes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721997430825/453fc8c2-b713-4b41-9f09-8b308345aa10.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> NavGraphBuilder.<span class="hljs-title">nested</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    navigation(
        startDestination = Screen.Fifth,
        route = Route.Nested::<span class="hljs-class"><span class="hljs-keyword">class</span></span>
    ) {
        <span class="hljs-comment">// code for nested navigation</span>
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> NavGraphBuilder.<span class="hljs-title">main</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    navigation(
        startDestination = Screen.First,
        route = Route.Main::<span class="hljs-class"><span class="hljs-keyword">class</span></span>
    ) {
        <span class="hljs-comment">// code for main navigation</span>
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Navigation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> navController = rememberNavController()

    NavHost(
        navController = navController,
        startDestination = Route.Main,
        route = Route.Root::<span class="hljs-class"><span class="hljs-keyword">class</span></span>
    ) {
        main(navController)
        nested(navController)
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    ...
    Button(onClick = { navController.navigate(Route.Nested) }) {
        Text(<span class="hljs-string">"Nested"</span>)
    }
}
</code></pre>
<p>With such changes, we can still navigate between graphs. There is no problem calling the <code>Fourth</code> screen from the nested graph. Let's try to achieve that by adding a way for the <code>Sixth</code> screen to open a <code>Fourth</code> screen.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">SixthScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    ...
    Button(onClick = {
        navController.navigate(Screen.Fourth(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Doe"</span>)) {
            Text(<span class="hljs-string">"John Doe Screen"</span>)
        }
    }
</code></pre>
<p>We can now modify the <code>Fourth</code> screen and add a button that will navigate back to the <code>main</code> graph instead of popping back the stack. This way, we can close the <code>nested</code> graph immediately and remove all its child screens from the backstack. The <code>navigate()</code> builder has a <code>popUpTo()</code> method that allows us to remove destinations from the backstack. We can pass the destination to which we want to pop back. There is also the <code>inclusive</code> parameter to remove the passed destination from the backstack as well.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FourthScreen</span><span class="hljs-params">(...)</span></span> {
    ...
    Button(
        onClick = {
            navController.navigate(Route.Main) {
                popUpTo(Route.Main)
            }
        }
    ) {
        Text(<span class="hljs-string">"MAIN"</span>)
    }
}
</code></pre>
<p>We can close the <code>nested</code> graph even quicker, while opening the <code>Fourth</code> screen from the <code>Sixth</code> all we need to do is use <code>popUpTo()</code> method with the <code>Route.Nested</code> parameter.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">SixthScreen</span><span class="hljs-params">(...)</span></span> {
    ...
    Button(onClick = {
        navController.navigate(Screen.Fourth(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Doe"</span>)) {
            popUpTo(Route.Nested)
        }
    }) {
        Text(<span class="hljs-string">"John Doe Screen"</span>)
    }
}
</code></pre>
<p>You can combine these functions in various ways to achieve the desired behavior. For instance, you can <code>pop</code> a screen before navigating to a new one, or you can remove entire navigation graphs from the backstack. This flexibility allows you to manage your app's navigation flow precisely.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721997669507/6a050685-bdbf-4139-8d5e-1f59d3927319.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-bottom-navigation">Bottom Navigation</h2>
<p>Yet another thing that is widely common in mobile apps nowadays is the bottom navigation. Let's extend the project with one more feature! We need to add three new screens: the <code>Eighth</code> screen, which will be the main screen that holds the bottom menu and is a container for the tabs, and the <code>Ninth</code> screen and <code>Tenth</code> screen. Inside the <code>Eighth</code> screen, we will add a new <code>NavHost</code> that will build its own graph and handle switching tabs. We will also use the <code>BottomNavigation</code> Jetpack Compose control to create the bottom bar view and its items.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">EighthScreen</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> navController = rememberNavController()

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> add bottom navigation</span>
        },
    ) { innerPadding -&gt;
        NavHost(
            modifier = Modifier.padding(innerPadding),
            navController = navController,
            startDestination = Screen.Eighth.Tab.Home,
        ) {
            composable&lt;Screen.Eighth.Tab.Home&gt; {
                NinthScreen()
            }

            composable&lt;Screen.Eighth.Tab.Edit&gt; {
                TenthScreen()
            }
        }
    }
}
</code></pre>
<p>The new <code>NavHost</code> has its own <code>navController</code> and <code>startDestination</code>. When we enter the screen, the item displayed as the first tab will always be the <code>Ninth</code> screen. The local <code>navController</code> is used to navigate between tabs. The <code>BottomNavigation</code> control is quite helpful. It will render the bottom bar with necessary elements such as <strong>icon</strong>, <strong>label</strong>, and <strong>selected</strong> state, and even adds a slight dim to the selected item. But to do so, we need to provide information about the tabs. Like in every other type of navigation, the displayed screens need their own <code>route</code>/<code>destination</code>, so we need to create a new <code>sealed class</code> for the tabs inside the current <code>Screen.kt</code> file.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Screen</span> </span>{
    ...
    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Eighth : Screen() {
        <span class="hljs-meta">@Serializable</span>
        <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tab</span></span>(<span class="hljs-keyword">val</span> icon: ICON, <span class="hljs-keyword">val</span> label: String) : Screen() {
            <span class="hljs-meta">@Serializable</span>
            <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Home : Tab(icon = ICON.HOME, label = <span class="hljs-string">"Home"</span>)

            <span class="hljs-meta">@Serializable</span>
            <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Edit : Tab(icon = ICON.EDIT, label = <span class="hljs-string">"Edit"</span>)

            <span class="hljs-meta">@Serializable</span>
            <span class="hljs-keyword">enum</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ICON</span> </span>{
                HOME, EDIT
            }
        }
    }
}
</code></pre>
<p>Now we can create the bottom navigation tabs.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">BottomBar</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    <span class="hljs-keyword">val</span> tabs = listOf(
        Screen.Eighth.Tab.Home,
        Screen.Eighth.Tab.Edit,
    )

    <span class="hljs-keyword">val</span> backstackEntry <span class="hljs-keyword">by</span> navController.currentBackStackEntryAsState()
    <span class="hljs-keyword">val</span> currentDestination = backstackEntry?.destination

    BottomNavigation {
        tabs.forEach { tab -&gt;
            TabItem(tab, currentDestination, navController)
        }
    }
}
</code></pre>
<p>The <code>BottomBar</code> is a composable function that is responsible for managing the elements within the tabs container. Inside this function, we need to define the elements, referred to as <code>tabs</code>, that will be displayed in the bottom bar. These tabs are specified as a list, which includes <code>Screen.Eighth.Tab.Home</code> and <code>Screen.Eighth.Tab.Edit</code>.</p>
<p>To keep track of the current screen, we utilize the <code>currentBackStackEntryAsState()</code> function. This function helps us obtain the current destination by monitoring changes in the <code>navController</code>. Whenever the <code>navController</code> undergoes changes due to navigation actions like <code>navigate()</code> or <code>pop()</code>, the <code>currentBackStackEntryAsState()</code> function updates the value, triggering a recomposition of the UI. This means that the top entry on the backstack is returned, allowing us to determine what is currently displayed on the screen.</p>
<p>By retrieving the <code>destination</code> from the backstack entry, we can access detailed information about the current screen. This setup ensures that the bottom navigation bar is dynamic and responsive to changes in the navigation state.</p>
<p>The <code>BottomNavigation</code> control takes a few parameters, and the last one is the <code>content: @Composable RowScope.() -&gt; Unit</code>, which will be responsible for creating the bottom navigation view. For each tab that we want to display, we should create a proper UI element. We can create an extension function for <code>RowScope</code> that will be responsible for providing the <code>BottomNavigationItem</code> for each tab.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> RowScope.<span class="hljs-title">TabItem</span><span class="hljs-params">(
    tab: <span class="hljs-type">Screen</span>.<span class="hljs-type">Eighth</span>.<span class="hljs-type">Tab</span>,
    currentDestination: <span class="hljs-type">NavDestination</span>?,
    navController: <span class="hljs-type">NavHostController</span>,
)</span></span> {
    BottomNavigationItem(
        icon = { Icon(imageVector = tab.icon.toVector(), contentDescription = <span class="hljs-string">"navigation_icon_<span class="hljs-subst">${tab.label}</span>"</span>) },
        label = { Text(tab.label) },
        selected = currentDestination?.hierarchy?.any { it == tab } == <span class="hljs-literal">true</span>,
        onClick = {
            navController.navigate(tab) {
                navController.graph.startDestinationRoute?.let { popUpTo(it) }
                launchSingleTop = <span class="hljs-literal">true</span>
            }
        },
    )
}

<span class="hljs-comment">// helper function for transforming enum to vectorIcon</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> Screen.Eighth.Tab.ICON.<span class="hljs-title">toVector</span><span class="hljs-params">()</span></span> = <span class="hljs-keyword">when</span> (<span class="hljs-keyword">this</span>) {
    Screen.Eighth.Tab.ICON.HOME -&gt; Icons.Default.Home
    Screen.Eighth.Tab.ICON.EDIT -&gt; Icons.Default.Edit
}
</code></pre>
<p>The <code>selected</code> state is calculated by checking if the current destination is the same as the tab of the current item. The <code>onClick</code> action is responsible for navigating to the clicked tab.</p>
<p>Since we want only one active screen inside the tabs container we need to <code>pop</code> it. This will cause dropping other element from the back stack. We can also add the <code>launchSingleTop</code> which will ensure that the tab is not preserved, and will be recreated with every click.</p>
<p>Last thing to do is to add an entry point in the main graph.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> NavGraphBuilder.<span class="hljs-title">main</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    ...
    composable&lt;Screen.Eighth&gt; {
        EighthScreen()
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreen</span><span class="hljs-params">(navController: <span class="hljs-type">NavHostController</span>)</span></span> {
    ...
    Button(onClick = { navController.navigate(Screen.Eighth) }) {
        Text(<span class="hljs-string">"Bottom"</span>)
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722226312723/326dc4d1-e890-46fc-900a-34c57e8687be.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-coroutines">Coroutines</h1>
<p>The last topic we will cover in this post is asynchronous operations. As mentioned earlier, various navigation libraries like <a target="_blank" href="https://hashnode.com/post/clypbla0r000909l4gov25akn">Decompose</a>, Appyx, and Voyager offer their own business logic container objects where asynchronous operations can be managed effectively.</p>
<p>In the context of Jetpack Compose, we will be utilizing <code>ViewModels</code> to manage these asynchronous tasks. <code>ViewModels</code> have recently been integrated into the Compose Multiplatform library, making them a versatile choice. This integration allows us to leverage the full power of <code>ViewModels</code> while building cross-platform applications with Compose.</p>
<p>It's important to note that even though Appyx and Voyager come with their own mechanisms for handling business logic and async operations, they still provide the flexibility to use <code>ViewModels</code> if you prefer. This means you can choose the approach that best fits your project's architecture and requirements.</p>
<p>The first thing to add is the proper dependency according to the <a target="_blank" href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-viewmodels.html">documentation</a>.</p>
<pre><code class="lang-kotlin">[versions]
common-viewmodels = <span class="hljs-string">"2.8.0"</span>

[libraries]
viewmodels-compose = { module = <span class="hljs-string">"org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose"</span>, version.ref = <span class="hljs-string">"common-viewmodels"</span> }
</code></pre>
<pre><code class="lang-kotlin">commonMain.dependencies {
    ...
    implementation(libs.viewmodels.compose)
}
</code></pre>
<p>The general usage of the <code>ViewModel</code> in Jetpack Compose is straightforward and bears a strong resemblance to the traditional Android approach. To begin with, we need to create a class that extends the <code>ViewModel</code>. This class will serve as the container for our business logic and asynchronous operations.</p>
<p>Within this <code>ViewModel</code> class, we have access to the <code>viewModelScope</code>, which is a specialized <code>CoroutineScope</code> tied to the lifecycle of the <code>ViewModel</code>. The significance of the <code>viewModelScope</code> is that it ensures any coroutines launched within it are automatically canceled when the <code>ViewModel</code> is destroyed. This lifecycle-aware behavior is crucial for managing resources efficiently and avoiding memory leaks.</p>
<p>For instance, if we need to perform a network request or a database operation, we can launch these tasks within the <code>viewModelScope</code>. This makes it easy to handle asynchronous operations without worrying about manually canceling coroutines when the <code>ViewModel</code> is no longer needed. Additionally, this setup allows us to write cleaner and more maintainable code, as the <code>ViewModel</code> encapsulates the logic and handles the lifecycle management for us.</p>
<p>Let's create a simple <code>ViewModel</code> that will handle the countdown timer and the corresponding <code>Eleventh</code> screen for displaying the values.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EleventhViewModel</span> : <span class="hljs-type">ViewModel</span></span>() {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> _countDownText = MutableStateFlow(<span class="hljs-string">""</span>)
    <span class="hljs-keyword">val</span> countDownText: StateFlow&lt;String&gt; = _countDownText.asStateFlow()

    <span class="hljs-keyword">init</span> {
        viewModelScope.launch {
            <span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">10</span> downTo <span class="hljs-number">0</span>) {
                _countDownText.value = i.toString()
                delay(<span class="hljs-number">1000</span>)
            }
        }
    }
}
</code></pre>
<p>To use the <code>ViewModel</code>, we can utilize the <code>viewModel</code> function provided by the <code>lifecycle-viewmodel-compose</code> library. The function returns an existing view model or creates a new one in the scope. The created <code>ViewModel</code> is bound to the <code>viewModelStoreOwner</code> and will be retained as long as the scope is alive.</p>
<p>The source code of the <code>Eleventh</code> screen is quite simple and looks like all previously created screens.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">EleventhScreen</span><span class="hljs-params">(
    navController: <span class="hljs-type">NavHostController</span>,
    viewModel: <span class="hljs-type">EleventhViewModel</span> = viewModel { EleventhViewModel()</span></span> },
) {
    Column(...) {
        ..
        Countdown(viewModel)
    }
}

<span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Countdown</span><span class="hljs-params">(viewModel: <span class="hljs-type">EleventhViewModel</span>)</span></span> {
    <span class="hljs-keyword">val</span> countdownText = viewModel.countDownText.collectAsState().value
    Text(<span class="hljs-string">"COUNTDOWN: <span class="hljs-variable">$countdownText</span>"</span>)
}
</code></pre>
<p>After adding the created screen to the navigation, we can launch it from the <code>First</code> screen end examine the countdown functionality.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722227183303/3bc8166e-4d0b-44e7-aa60-12f916a4cfcd.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-summary">Summary</h1>
<p>In this post, we covered the basics of Jetpack Compose navigation. The library is well-documented, and you will surely find many posts, videos, and other resources to help you understand the navigation better. Jetpack Compose navigation is a powerful tool that allows you to create complex navigation structures with ease. The library has been available for Android for a long time, and now it's available for multiplatform projects. The multiplatform version of the library is still in <strong>alpha</strong> version, but in my opinion, it's ready to use in production. The library is a great choice for developers who want to create modern and complex navigation structures in their applications.</p>
<p>In my previous posts, I covered the <a target="_blank" href="https://hashnode.com/post/clypbla0r000909l4gov25akn">Decompose</a>, Appyx, and Voyager navigation libraries. Now I can say that my personal favorite is the <code>JetpackCompose</code> navigation, as it will be the most popular and widely used in the future, with great support from the community and the Jetbrains team. The Compose Multiplatform is growing rapidly, and I'm sure that in the near future, we will see a lot of great libraries and tools that will help us create modern and complex applications. But all of them are great, and you should choose what fits your needs best.</p>
<p>When I began writing a post about <a target="_blank" href="https://github.com/mkonkel/GameShop">Fullstack Kotlin Developer</a>, I was thinking about the navigation library that I would use in the project. As there was no official or suggested way of handling the navigation in the multiplatform project, I chose the <code>Decompose</code> library. However, after adopting the <code>JetpackCompose</code> navigation and the <code>Viewmodels</code> to <code>Compose Multiplatform</code>, I would definitely recommend it as the best choice for your project, and I'm sure that I will use it in all of my future projects as well.</p>
<blockquote>
<p>In this project, I will explore several popular navigation libraries for app development, emphasizing the use of JetpackCompose for managing navigation in a multiplatform context. I will cover linear navigation, passing parameters safely, nested navigation, bottom navigation, and handling asynchronous operations with coroutines using ViewModels. The content highlights how to set up navigation components, manage navigation state, and integrate bottom navigation into your app, along with a practical guide on using ViewModels for managing asynchronous tasks. This article aims to demonstrate how JetpackCompose is a versatile and modern solution for implementing complex navigation structures in your applications.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Compose Multiplatform Navigation Solutions - Appyx]]></title><description><![CDATA[Explore Appyx for smooth Compose Multiplatform navigation using nodes, coroutines; learn integration, features, future developments]]></description><link>https://michalkonkel.dev/compose-multiplatform-navigation-solutions-appyx</link><guid isPermaLink="true">https://michalkonkel.dev/compose-multiplatform-navigation-solutions-appyx</guid><category><![CDATA[appyx]]></category><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[navigation]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[mobile app architecture]]></category><category><![CDATA[coroutines]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Wed, 09 Oct 2024 22:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730840161721/c0b50b50-121d-44e3-9101-2dd666571aa8.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the upcoming posts, I will thoroughly explore several popular navigation libraries that are essential for effective app development. These libraries play a crucial role in managing app navigation, ensuring a smooth and intuitive user experience. In today's episode, we will focus on the <a target="_blank" href="https://github.com/bumble-tech/appyx">Appyx library</a>. We will examine how Appyx handles various navigation scenarios, its integration process.</p>
<p>Choosing a navigation library for your Compose Multiplatform project can be challenging. The decision requires careful consideration of your project's requirements and future scalability, understanding the strengths and limitations of each library is crucial to avoid potential pitfalls and ensure a seamless development process.</p>
<p>Showcase application assumptions:</p>
<ul>
<li><p>Application should allow us to navigate from one screen to another.</p>
</li>
<li><p>Application should allow to pass some parameters from first to second screen.</p>
</li>
<li><p>Application should handle the screen rotation without loosing data.</p>
</li>
<li><p>Application should handle the Tab Navigation.</p>
</li>
<li><p>Application should handle the async operations with coroutines.</p>
</li>
</ul>
<blockquote>
<p><em>The project is available in the</em> <a target="_blank" href="https://github.com/mkonkel/AppyxNavigation"><em>GitHub</em></a> <em>repository.</em></p>
</blockquote>
<hr />
<h1 id="heading-dependencies">Dependencies</h1>
<p>Base project setup, as always, is made with <a target="_blank" href="https://kmp.jetbrains.com/">Kotlin Multiplatform Wizard</a>. We also need to add <a target="_blank" href="https://kmp.jetbrains.com/">Appyx</a> as it is the core element we want to examine. Appyx consists of three main libraries that complement each other: <strong><em>navigation</em></strong>, <strong><em>interactions</em></strong>, and <strong><em>components</em></strong>. This allows us to create a fully customized application.</p>
<p><code>libs.versions.toml</code></p>
<pre><code class="lang-kotlin">[versions]
appyx = <span class="hljs-string">"2.0.1"</span>

[libraries]
appyx-navigation = { module = <span class="hljs-string">"com.bumble.appyx:appyx-navigation"</span>, version.ref = <span class="hljs-string">"appyx"</span> }
appyx-interactions = { module = <span class="hljs-string">"com.bumble.appyx:appyx-interactions"</span>, version.ref = <span class="hljs-string">"appyx"</span> }
appyx-components-backstack = { module = <span class="hljs-string">"com.bumble.appyx:backstack"</span>, version.ref = <span class="hljs-string">"appyx"</span> }
</code></pre>
<p>Freshly added dependencies need to be synced with the project and added to the <code>build.gradle.kts</code>.</p>
<pre><code class="lang-kotlin">sourceSets {
    commonMain.dependencies {
        ...
        implementation(libs.appyx.navigation)
        implementation(libs.appyx.interactions)
        api(libs.appyx.components.backstack)
    }
}
</code></pre>
<h1 id="heading-appyx-introduction">Appyx Introduction</h1>
<p>With dependencies added, we can start to create the navigation. Following the Appyx <a target="_blank" href="https://bumble-tech.github.io/appyx/navigation/">documentation</a>, we can notice one major thing: Appyx gives us flexibility in interpreting the term "navigation." Most modern libraries/solutions focus on how to get from one screen to another, but Appyx gives us the possibility to create navigation that is not only about screens but "viewport." It can be whatever you can imagine, for example, spinning the carousel.</p>
<h2 id="heading-node">Node</h2>
<p>Nevertheless, we will focus on traditional <code>Stack</code> navigation. There are some basic blocks that we need to use. The first one is <code>Node</code>, which is a representation of the structure (in our case, the screen). Each node can hold other nodes, and they are called <strong><em>children</em></strong>. The <code>node</code> is a standalone unit with its own:</p>
<ul>
<li><p><a target="_blank" href="https://bumble-tech.github.io/appyx/components/">AppyxComponent</a> - in our case, it will be a <code>back stack</code>, with simple linear navigation. The element at the front is considered active, others are stashed. It can never be empty. It has some basic helper functions like <code>push</code>, <code>pop</code>, <code>replace</code>, and a default back handler.</p>
</li>
<li><p><a target="_blank" href="https://bumble-tech.github.io/appyx/navigation/features/lifecycle/">Lifecycle</a> - it's a multiplatform interface that notifies the component about the state changes on the platform. For example, on the Android platform, it is implemented with <code>AndroidLifecycle</code>.</p>
</li>
<li><p>State Restoration after orientation changes</p>
</li>
<li><p>View, which is created with <code>@Composable</code></p>
</li>
<li><p>Business logic</p>
</li>
<li><p>Plugins - since <code>Nodes</code> should be kept lean, the plugins are used to add additional functionality, for example, <code>NodeLifecycleAware</code> that allows listening to the lifecycle events.</p>
</li>
</ul>
<p>The <code>nodes</code> can be as small as you want to keep the complexity of your logic low and encapsulated, and extracted to the <strong>children</strong> to compose the navigation process. With the nodes, your navigation can work as a tree with multiple branches responsible for different processes. Some parts of the tree are active - visible on the screen, while others are stashed. To change what's currently active, we will use the component; the change will look like navigation by adding or removing nodes.</p>
<p>Such an approach creates a <a target="_blank" href="https://bumble-tech.github.io/appyx/navigation/features/scoped-di/">Scoped DI</a>, a situation where if the parent node is destroyed, all of its children nodes and related objects are released. There is also <a target="_blank" href="https://bumble-tech.github.io/appyx/navigation/features/childaware/">ChildAwareAPI</a> that helps with communication between the parent and dynamically added child.</p>
<h2 id="heading-rootnode">RootNode</h2>
<p>After that short introduction it's time to code. First thing that we need to create is <strong><em>RootNode</em></strong>.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RootNode</span></span>(
    nodeContext: NodeContext,
) : LeafNode(nodeContext) {

    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span>)</span></span> {
        Column(
            modifier = Modifier.fillMaxSize().then(modifier),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(<span class="hljs-string">"Hello Appyx!"</span>)
        }
    }
}
</code></pre>
<p>Similarly, as in the <a target="_blank" href="https://hashnode.com/post/clypbla0r000909l4gov25akn">Decompose</a> library, we need to provide context. The <code>NodeContext</code> is created on the host platform (e.g., Android's MainActivity) and is passed down to all the descendants. It ensures the support of lifecycle and keeps the structured hierarchy of children nodes. The <code>LeafNode</code> uses the context to handle all the lifecycle events, manage plugins, provide the coroutines scope, and manage the children creation to keep the structured nodes hierarchy mentioned in <strong><em>scoped DI</em></strong>. It also forces us to implement a <strong><em>@Composable</em></strong> function <code>Content</code> that will be used to create the view.</p>
<h3 id="heading-android">Android</h3>
<p>Let's connect the <code>RootNode</code> with the hosts. For Android, we need to use <strong><em>MainActivity</em></strong> and inherit from the <code>NodeComponentActivity()</code>, which integrates Android with Appyx under the hood (if you don't want to inherit from ready-made solutions, you can implement ActivityIntegrationPoint yourself). Then we need to create the <code>NodeHost</code> (which is responsible for providing <strong><em>nodeContext</em></strong>) and provide it with <strong><em>lifecycle</em></strong>.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">NodeComponentActivity</span></span>() {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)

        setContent {
            MaterialTheme {
                NodeHost(
                    lifecycle = AndroidLifecycle(LocalLifecycleOwner.current.lifecycle),
                    integrationPoint = appyxIntegrationPoint
                ) { nodeContext -&gt;
                    RootNode(nodeContext)
                }
            }
        }
    }
}
</code></pre>
<h3 id="heading-ios">iOS</h3>
<p>With the iOS we just need to create proper host the <code>IosNodeHost</code> with default <code>IntegrationPoint</code> as it is a <code>@Compose</code> function.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">MainViewController</span><span class="hljs-params">()</span></span> = ComposeUIViewController {
    IosNodeHost(
        modifier = Modifier,
        integrationPoint = MainIntegrationPoint(),
        onBackPressedEvents = backEvents.receiveAsFlow()
    ) { nodeContext -&gt;
        RootNode(nodeContext)
    }
}
</code></pre>
<h1 id="heading-linear-navigation">Linear Navigation</h1>
<p>The basic setup was done, we were able to display initial screen with the text. Now we can add children screens. The screen definition need to be defined as <code>Parcelable</code> it will tell the node where we ant to go. The <code>Parcelable</code>is a part of Appyx library and it's expect/actual class so it has a common definition that is implemented differently on platforms. For android platform we need to add the support od <a target="_blank" href="https://developer.android.com/kotlin/parcelize">kotlin-parcelizeplugin to use <code>@</code></a><code>Parcelize</code> annotation.</p>
<pre><code class="lang-kotlin">plugins {
    ...
    id(<span class="hljs-string">"kotlin-parcelize"</span>)
}
</code></pre>
<p>Now we can define some navigation targets to enhance our app's functionality. To do this, we need to specify the screens we want to navigate to. Each screen should be defined as a <code>Parcelable</code> object, which will inform the node about the destination.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavTarget</span> : <span class="hljs-type">Parcelable {</span></span>
    <span class="hljs-meta">@Parcelize</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> FirstScreen : NavTarget()

    <span class="hljs-meta">@Parcelize</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> SecondScreen : NavTarget()
}
</code></pre>
<p>Targets are defined, so now the <code>RootNode</code> needs to be modified to handle the <code>BackStack</code>component and provide a way to navigate between different screens. The first change we need to make is to transform the <code>RootNode</code> from being merely a <code>LeafNode</code> to a <code>Node&lt;&gt;</code>. A <code>LeafNode</code> is a simple node that cannot have children and is primarily used to display static content. On the other hand, a <code>Node&lt;&gt;</code> is more versatile as it can have child nodes and is capable of managing navigation between them.</p>
<p>To achieve this, we need to update the <code>RootNode</code> class to include the <code>BackStack</code>component, which will keep track of the navigation history. This allows the app to handle back navigation correctly and ensures that users can move seamlessly between different screens.</p>
<p>The <code>Node</code> requires the <code>NavTarget</code> to be defined and the <code>buildChildNode</code> function to be implemented. These two elements are crucial because they handle the creation and management of the child nodes. The <code>NavTarget</code> serves as a blueprint for the different screens or destinations within the app, while the <code>buildChildNode</code> function is responsible for constructing these child nodes whenever navigation occurs.</p>
<p>Additionally, another important aspect to consider is the <code>appyxComponent</code> parameter. This parameter plays a significant role in defining how the nodes will be managed and navigated. It determines the behavior and lifecycle of the nodes, ensuring that they are correctly instantiated, displayed, and disposed of as the user navigates through the app.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">backstack</span><span class="hljs-params">(nodeContext: <span class="hljs-type">NodeContext</span>)</span></span>: BackStack&lt;NavTarget&gt; = BackStack(
    model = BackStackModel(
        initialTarget = NavTarget.FirstScreen,
        savedStateMap = nodeContext.savedStateMap,
    ),
    visualisation = { BackStackFader(it) }
)
</code></pre>
<p>The destination nodes may look like the following:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstNode</span></span>(
    nodeContext: NodeContext
) : LeafNode(nodeContext = nodeContext) {
    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span>)</span></span> {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(<span class="hljs-string">"Hello from the First Node!"</span>)
        }
    }
}
</code></pre>
<p>To enable navigation between different screens, we will add simple lambda expressions. These lambda expressions will be invoked within the child nodes, but the actual handling will occur in the root node. This approach allows us to centralize the navigation logic, making it easier to manage and maintain.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstNode</span></span>(
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onButtonClick: () -&gt; <span class="hljs-built_in">Unit</span>
) : LeafNode(nodeContext = nodeContext) {
    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span>)</span></span> {
        ...
        TextButton(onClick = onButtonClick) {
            Text(<span class="hljs-string">"Go to Second Node"</span>)
        }
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RootNode</span></span>(
    nodeContext: NodeContext,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> backstack: BackStack&lt;NavTarget&gt; = backstack(nodeContext),
) : Node&lt;NavTarget&gt;(
    appyxComponent = backstack,
    nodeContext = nodeContext,
) {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">buildChildNode</span><span class="hljs-params">(navTarget: <span class="hljs-type">NavTarget</span>, nodeContext: <span class="hljs-type">NodeContext</span>)</span></span>: Node&lt;*&gt; =
        <span class="hljs-keyword">when</span> (navTarget) {
            NavTarget.FirstScreen -&gt; FirstNode(nodeContext) {
                backstack.push(NavTarget.SecondScreen)
            }
            NavTarget.SecondScreen -&gt; SecondNode(nodeContext) {
                backstack.push(NavTarget.FirstScreen)
            }
        }
}
</code></pre>
<p>The last step involves adding the <a target="_blank" href="https://bumble-tech.github.io/appyx/interactions/usage/?h=appyxnavigationcontainer#in-the-scope-of-appyx-navigation"><strong>AppyxNavigationContainer</strong></a>. This container is crucial as it will manage the navigation and render the content of the nodes that we have added.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span>)</span></span> {
    AppyxNavigationContainer(appyxComponent = backstack)
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721627965690/1d3f3353-1f23-4d6b-802b-698c6b1c304b.gif" alt class="image--center mx-auto" /></p>
<p>You can experiment with different visualisations, for example <code>BackStackFader</code>, <code>BackStackSlider</code>, <code>BackStackParallax</code>or other mentioned in the <a target="_blank" href="https://bumble-tech.github.io/appyx/components/backstack/">documentation</a></p>
<h1 id="heading-tab-navigation">Tab Navigation</h1>
<p>To handle the bottom navigation feature, we need to use a <a target="_blank" href="https://bumble-tech.github.io/appyx/components/spotlight/">Spotlightcomponent</a>. This component functions similarly to an Android view pager, allowing us to manage multiple nodes simultaneously while keeping one of them active and visible at any given time. The Spotlight component is designed to facilitate smooth transitions and intuitive navigation within the app.</p>
<p>The principle is the same as with linear navigation, where we use a <code>backstack</code> to manage the navigation flow. However, for bottom navigation, we switch from using <code>backstack</code> to <code>spotlight</code>. This switch enables us to handle multiple nodes more efficiently and provides a better user experience by maintaining the state of each node while navigating between them.</p>
<h2 id="heading-spotlight">Spotlight</h2>
<p>To implement this, we first need to define the nodes that will be part of the bottom navigation. Each node represents a different screen or feature within the app. Once the nodes are defined, we can use the Spotlight component to manage their visibility and transitions. Additionally, the Spotlight component offers various customization options, such as animations and transition effects, to enhance the user experience.</p>
<pre><code class="lang-kotlin">appyx-components-spotlingh = { module = <span class="hljs-string">"com.bumble.appyx:spotlight"</span>, version.ref = <span class="hljs-string">"appyx"</span> }
</code></pre>
<p>Let's create new navigation targets for tabbed navigation.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SpotlightNavTarget</span> : <span class="hljs-type">Parcelable {</span></span>
    <span class="hljs-meta">@Parcelize</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> ThirdScreen : SpotlightNavTarget()

    <span class="hljs-meta">@Parcelize</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> FourthScreen : SpotlightNavTarget()
}
</code></pre>
<p>Now we need to create a parent node that will hold the spotlight component.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SpotlightNode</span></span>(
    nodeContext: NodeContext,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> model: SpotlightModel&lt;SpotlightNavTarget&gt; = spotlightModel(nodeContext),
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> spotlight: Spotlight&lt;SpotlightNavTarget&gt; = Spotlight(
        model = model,
        visualisation = { SpotlightSlider(it, model.currentState) }
    ),
) : Node&lt;SpotlightNavTarget&gt;(
    appyxComponent = spotlight,
    nodeContext = nodeContext,
)
</code></pre>
<p>We have to provide <code>SpotlightModel</code> and <code>SpotlightVisualisation</code>. One will handle navigation, and the other will handle the animation. The model takes a list of elements available to be displayed in the carousel and the initial index of the default active tab.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">spotlightModel</span><span class="hljs-params">(nodeContext: <span class="hljs-type">NodeContext</span>)</span></span> = SpotlightModel(
    items = listOf(SpotlightNavTarget.ThirdScreen, SpotlightNavTarget.FourthScreen),
    initialActiveIndex = <span class="hljs-number">0f</span>,
    savedStateMap = nodeContext.savedStateMap
)
</code></pre>
<p>Last thing to do is to create a UI representation of the screen, we will use Scaffold and default button</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span>)</span></span> {
    Scaffold(
        bottomBar = {
            Row(Modifier.background(Color.White)) {
                TextButton(modifier = Modifier.weight(<span class="hljs-number">1f</span>), onClick = { spotlight.first() }) {
                    Text(text = <span class="hljs-string">"Third"</span>)
                }
                TextButton(modifier = Modifier.weight(<span class="hljs-number">1f</span>), onClick = { spotlight.last() }) {
                    Text(text = <span class="hljs-string">"Fourth"</span>)
                }
            }
        }
    ) { paddings -&gt;
        AppyxNavigationContainer(modifier = Modifier.padding(paddings), appyxComponent = spotlight)
    }
}
</code></pre>
<p>The targets nodes will be exactly the same but with a different text and a background.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThirdNode</span></span>(
    nodeContext: NodeContext,
) : LeafNode(nodeContext = nodeContext) {
    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span>)</span></span> {
        Column(
            modifier = Modifier.fillMaxSize().background(Color.Magenta),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(<span class="hljs-string">"Hello from the Third Node!"</span>)
        }
    }
}
</code></pre>
<p>The solution is ready to use, as it was designed to work just out of the box. We need to add only the entry point to our existing navigation. We need to add <code>TabScreen</code> as a <code>NavTarget</code> in the linear navigation and a button in <code>FirstNode</code> that will run the <strong><em>tabbed navigation</em></strong> feature.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721628891943/4e4aeb95-5c4e-45d2-b39d-32559b4f2db2.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-material3-support">Material3 Support</h2>
<p><code>Appyx</code> also provides <a target="_blank" href="https://m3.material.io/">Material3</a> support with an out-of-the-box solution for bottom navigation, allowing developers to create a seamless and visually appealing navigation experience using built-in components. The material support library leverages the <a target="_blank" href="https://bumble-tech.github.io/appyx/components/spotlight/">spotlight</a> component under the hood, which is a powerful tool for managing navigation transitions and animations. To utilize this feature, we need to add another dependency to the project. This additional dependency ensures that the spotlight component is available, enabling smooth integration and functionality of the bottom navigation within our application. By incorporating Material3 support, we can enhance the user interface and provide a more cohesive and modern look and feel to our app's navigation system.</p>
<pre><code class="lang-ini"><span class="hljs-attr">appyx-utils-material</span> = { module = <span class="hljs-string">"com.bumble.appyx:utils-material3"</span>, version.ref = <span class="hljs-string">"appyx"</span> }
</code></pre>
<pre><code class="lang-kotlin">commonMain.dependencies {
    ...
    api(libs.appyx.utils.material)
}
</code></pre>
<p>After syncing the project, we will reach the <code>AppyxNavItem</code>, which will be used in bottom navigation, and the <code>AppyxMaterial3NavNode</code>, responsible for navigation. The creation of the <code>TabNavigationItems</code> is straightforward and similar to the previously used linear navigation. We need to create <code>destinations</code>; in our case, these will be the enums that represent the screens/nodes.</p>
<pre><code class="lang-ini">@Parcelize
enum class TabNavigationItems : Parcelable {
    FIRST_DESTINATION, SECOND_DESTINATION<span class="hljs-comment">;</span>
}
</code></pre>
<p>Now we can create the <code>resolver</code> that will be responsible for creating the bottom bar. It takes the defined <strong><em>destination</em></strong> and creates the proper navigation items, with <strong><em>text</em></strong>, <strong><em>icons</em></strong>, and a <strong>lambda</strong> that will create the desired <strong><em>nodes</em></strong>.</p>
<pre><code class="lang-ini">companion object {
    val resolver: (TabNavigationItems) -&gt; <span class="hljs-attr">AppyxNavItem</span> = { navBarItem -&gt;
        when (navBarItem) {
            FIRST_DESTINATION -&gt; AppyxNavItem(
                <span class="hljs-attr">text</span> = <span class="hljs-string">"Third"</span>,
                <span class="hljs-attr">unselectedIcon</span> = Icons.Sharp.Home,
                <span class="hljs-attr">selectedIcon</span> = Icons.Filled.Home,
                <span class="hljs-attr">node</span> = { ThirdNode(it) }
            )

            SECOND_DESTINATION -&gt; AppyxNavItem(
                <span class="hljs-attr">text</span> = <span class="hljs-string">"Fourth"</span>,
                <span class="hljs-attr">unselectedIcon</span> = Icons.Sharp.AccountBox,
                <span class="hljs-attr">selectedIcon</span> = Icons.Filled.AccountBox,
                <span class="hljs-attr">node</span> = { FourthNode(it) }
            )
        }
    }
}
</code></pre>
<p>The last thing to do is to create proper starting node.</p>
<pre><code class="lang-ini">class TabNode(
    nodeContext: NodeContext,
) : AppyxMaterial3NavNode&lt;TabNavigationItems&gt;(
    <span class="hljs-attr">nodeContext</span> = nodeContext,
    <span class="hljs-attr">navTargets</span> = TabNavigationItems.entries,
    <span class="hljs-attr">navTargetResolver</span> = TabNavigationItems.resolver,
    <span class="hljs-attr">initialActiveElement</span> = TabNavigationItems.FIRST_DESTINATION,
)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721629592185/a5dd9544-ec54-478d-8806-0d34169653f3.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-coroutines">Coroutines</h1>
<p>There is no official approach on how to handle coroutines inside the <strong><em>Nodes</em></strong>, but there are several strategies we can employ. One common method is to utilize the <strong><em>NodeLifecycle</em></strong>, which provides both the <code>lifecycle</code> and <code>lifecycleScope</code>. This allows us to manage coroutines effectively within the node's lifecycle, as shown in the example.</p>
<blockquote>
<p>The <a target="_blank" href="https://hashnode.com/post/clypbla0r000909l4gov25akn">Decompose</a> (which I mentioned in a previous post) provides us with default support for coroutines inside the library core elements - Component.</p>
</blockquote>
<p>Additionally, we can leverage the <code>lifecycle</code> to add an <code>observer</code> using <code>PlatformLifecycleEventObserver</code>. This observer can be used to create and manage a <code>coroutineScope</code>, ensuring that coroutines are properly handled throughout the node's lifecycle events.</p>
<p>Another option is to use the scope provided by the @Composable view with <code>rememberCoroutineScope()</code>. This approach ties the coroutine scope to the composable's lifecycle, making it a convenient choice for managing coroutines within composable functions.</p>
<p>Moreover, we can mix these approaches to suit different needs and scenarios. For instance, we might use <code>NodeLifecycle</code> for some coroutines and <code>rememberCoroutineScope()</code> for others, depending on the specific requirements of our application. By combining these strategies, we can achieve a robust and flexible coroutine management system within our nodes.</p>
<p>Moving further I will extend the <code>SecondNode</code> with a countdown timer that will be started on the screen creation and update the text value.</p>
<pre><code class="lang-ini">    private val <span class="hljs-attr">countDownText</span> = mutableStateOf&lt;String&gt;(<span class="hljs-string">"0"</span>)

init {
    lifecycle.coroutineScope.launch {
        for (i in 10 downTo 0) {
            <span class="hljs-attr">countDownText.value</span> = i.toString()
            delay(1000)
        }
    }
}
</code></pre>
<pre><code class="lang-ini">@Composable
override fun Content(modifier: Modifier) {
    Column(...) {
        ...
        Spacer(<span class="hljs-attr">modifier</span> = Modifier.height(<span class="hljs-number">16</span>.dp))
        Text("Countdown: ${countDownText.value}")
    }
}
</code></pre>
<p>You should consider finding a more suitable place to hold your business logic than the <code>Node</code>. Ideally, this place should be capable of handling configuration changes and recreating the view while retaining the state. The <code>ViewModel</code> is an excellent choice for this purpose, as it is specifically designed to manage UI-related data in a lifecycle-conscious way. However, it's important to note that <code>ViewModel</code> is not currently a part of the Appyx library, so you will need to implement it yourself.</p>
<p>Appyx is actively working on adding <code>ViewModel</code> support, and you can express your interest and vote for this feature <a target="_blank" href="https://github.com/bumble-tech/appyx/issues/553">here</a>. This will help prioritize its development and integration into the library.</p>
<p>In the meantime, if you need to ensure that your application survives configuration changes, there is an official <a target="_blank" href="https://bumble-tech.github.io/appyx/2.x/navigation/features/surviving-configuration-changes/">guide</a> available. This guide provides detailed instructions and best practices for managing configuration changes effectively. By following this guide, you can ensure that your app remains robust and maintains its state across various configuration changes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721630302507/6e6c65d9-33d7-4979-92da-619e1a62cc5b.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-summary">Summary</h1>
<p>The <code>Appyx</code> library is a powerful tool that allows you to create fully customized navigation in your Compose Multiplatform application. It's a great solution for creating complex navigation structures, and it's easy to use. The library is tightly coupled with Jetpack Compose but doesn't provide a dedicated component to hold your business logic, so you are free to use your own solutions. The library is still in the development phase, waiting for <code>ViewModel</code> support as mentioned in the post. Therefore, it doesn't provide out-of-the-box support for coroutines. You need to handle it yourself, but it's not a big deal.</p>
<p>I hope this post has given you a good overview of the <code>Appyx</code> library and how you can use it to create navigation in your Compose Multiplatform application. If you have any questions or comments, please feel free to leave them below. I'd love to hear from you!</p>
<blockquote>
<p>In this post, we'll explore the Appyx library for Compose Multiplatform, covering its integration, navigation capabilities, and support for various scenarios such as linear navigation, tab navigation, and asynchronous operations with coroutines. We'll walk through setting up dependencies, creating nodes, managing navigation, and handling coroutines. Additionally, we'll touch upon Appyx's flexibility for custom navigation solutions and its ongoing development for enhanced features like ViewModel support. This guide aims to provide a comprehensive understanding of utilizing Appyx for robust app navigation.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Compose Multiplatform Navigation Solutions - Voyager]]></title><description><![CDATA[Explore Voyager, a navigation library for Compose Multiplatform projects, covering setup, screens, navigation, transitions, and state management]]></description><link>https://michalkonkel.dev/compose-multiplatform-navigation-solutions-voyager</link><guid isPermaLink="true">https://michalkonkel.dev/compose-multiplatform-navigation-solutions-voyager</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[navigation]]></category><category><![CDATA[mobile app development]]></category><category><![CDATA[mobile app architecture]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[Voyager]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Mon, 09 Sep 2024 04:51:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725857348574/7d16f862-ac0b-4833-a4df-52ce3586a173.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the upcoming posts, I will thoroughly explore several popular navigation libraries used in Compose Multiplatform projects. Today's post is about the <a target="_blank" href="https://voyager.adriel.cafe">Voyager</a> library. Choosing a navigation library for your Compose Multiplatform project can be a challenging task due to the variety of options available, each with its own unique features and benefits.</p>
<p>Selecting the right navigation library is crucial as it impacts the structure and flow of your application. An ideal navigation library should offer flexibility, ease of use, and robust performance to handle complex navigation scenarios. In this series, I aim to dive deep into the functionalities and advantages of different libraries to help you make an informed decision.</p>
<p>Showcase application assumptions:</p>
<ul>
<li><p>Application should allow us to navigate from one screen to another.</p>
</li>
<li><p>Application should allow to pass some parameters from first to second screen.</p>
</li>
<li><p>Application should handle the screen rotation without loosing data.</p>
</li>
<li><p>Application should handle the Tab Navigation.</p>
</li>
<li><p>Application should handle the async operations with coroutines.</p>
</li>
</ul>
<blockquote>
<p><em>The project is available in the</em> <a target="_blank" href="https://github.com/mkonkel/VoyagerNavigation"><em>GitHub</em></a> <em>repository.</em></p>
</blockquote>
<hr />
<h1 id="heading-dependencies">Dependencies</h1>
<p>Base project setup as always is made with <a target="_blank" href="https://kmp.jetbrains.com/">Kotlin Multiplatform Wizard,</a> we also need to add some <a target="_blank" href="https://voyager.adriel.cafe/">Voyager</a> as it is the core thing that we would like to examine.</p>
<pre><code class="lang-ini"><span class="hljs-section">[versions]</span>
<span class="hljs-attr">voyager</span> = <span class="hljs-string">"1.1.0-alpha04"</span>

<span class="hljs-section">[libraries]</span>
voyager - <span class="hljs-attr">navigator</span> = { module = <span class="hljs-string">"cafe.adriel.voyager:voyager-navigator"</span>, version.ref = <span class="hljs-string">"voyager"</span> }
voyager - <span class="hljs-attr">screenmodel</span> = { module = <span class="hljs-string">"cafe.adriel.voyager:voyager-screenmodel"</span>, version.ref = <span class="hljs-string">"voyager"</span> }
voyager - <span class="hljs-attr">transitions</span> = { module = <span class="hljs-string">"cafe.adriel.voyager:voyager-transitions"</span>, version.ref = <span class="hljs-string">"voyager"</span> }
</code></pre>
<pre><code class="lang-kotlin">commonMain.dependencies {
    ...
    implementation(libs.voyager.navigator)
    implementation(libs.voyager.screenmodel)
    implementation(libs.voyager.transitions)
}
</code></pre>
<h1 id="heading-voyager-introduction">Voyager Introduction</h1>
<p>A multiplatform navigation library built specifically for, and seamlessly integrated with, <a target="_blank" href="https://developer.android.com/jetpack/compose"><strong>Jetpack Compose</strong></a>. Voyager provides a robust and flexible solution for managing navigation in your applications. It supports various navigation patterns, including stack-based navigation, tab navigation, and more.</p>
<h2 id="heading-screens">Screens</h2>
<p>The basic structure for Voyager is the <a target="_blank" href="https://voyager.adriel.cafe/navigation#screen"><strong>Screen</strong></a> interface. Every screen in our applica<a target="_blank" href="https://voyager.adriel.cafe/navigation#screen">tion i</a>s essentially a class that includes a <code>@Composable</code> function responsible for providing the content to be displayed. Each screen-related class must implement this interface. Upon closer examination, we can see that the <code>Screen</code> interface is a straightforward contract with only one method to implement, which makes it easy to understand and use.</p>
<p>For screens that do not require any input parameters, we can use either an <code>object</code> or a <code>class</code>. This allows us to define simple, reusable screens without the need for additional setup. On the other hand, if a screen needs to accept some parameters, we can use a <code>data class</code>. This approach is particularly useful when we need to pass data between different screens, ensuring that each screen can be customized based on the provided parameters.</p>
<p>Let's add the screens with basic UI to the project</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreen</span> : <span class="hljs-type">Screen {</span></span>

    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(<span class="hljs-string">"First screen"</span>)
            Button(onClick = { <span class="hljs-comment">/*TODO*/</span> }) {
                Text(<span class="hljs-string">"Second Screen"</span>)
            }
        }
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecondScreen</span></span>(<span class="hljs-keyword">val</span> greetings: String) : Screen {

    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(<span class="hljs-string">"First screen"</span>)
            Spacer(modifier = Modifier.height(<span class="hljs-number">16</span>.dp))
            Text(<span class="hljs-string">"Greetings: <span class="hljs-variable">$greetings</span>}"</span>)
            Button(onClick = { <span class="hljs-comment">/*TODO*/</span> }) {
                Text(<span class="hljs-string">"Go Back"</span>)
            }
        }
    }
}
</code></pre>
<h1 id="heading-linear-navigation">Linear Navigation</h1>
<p>The second most important component in Voyager is the <a target="_blank" href="https://voyager.adriel.cafe/navigation#navigator"><strong>Navigator</strong>,</a> which is a Compose function built upon the internals of the Compose framework. The Navigator plays a crucial role in managing various aspects of the application. It handles the <strong><em>lifecycle</em></strong>, <strong><em>backPress, StateRestoration</em></strong> and the <strong><em>navigation.</em></strong></p>
<p>To obtain the navigator in any <code>Screen</code>, we need to use the <code>LocalNavigator</code> within the local composition. This is similar to how we use other elements in the <a target="_blank" href="https://developer.android.com/develop/ui/compose/compositionlocal">CompositionLocal</a>. The <code>LocalNavigator</code> must be provided at the root of the composition, typically within the <code>App()</code> function. By doing this, we ensure that the navigator is accessible throughout the entire composition tree, allowing for seamless navigation between different screens. This setup is essential for maintaining a consistent and manageable navigation structure in our application.</p>
<p>Let's obtain the <strong><em>navigator</em></strong> and <strong><em>push</em></strong> the <strong><em>SecondScreen</em></strong> from the <strong><em>FirstScreen</em></strong>. To achieve this, we need to instantiate the second screen within the function call. This process involves creating an instance of the <code>SecondScreen</code> class and then using the <code>push</code> method to navigate to it.</p>
<p>One interesting aspect to note is that <code>push</code> is an <strong><em>infix</em></strong> function. In Kotlin, infix functions allow us to call functions in a more natural and readable way, without the need for dots and parentheses. This makes the code cleaner and easier to understand. For example, instead of writing <code>navigator.push(SecondScreen())</code>, we can simply write <code>navigator push SecondScreen()</code>.</p>
<p>This infix notation enhances the readability of the code, making the navigation flow more intuitive and straightforward. By leveraging this feature, we can create a more elegant and maintainable navigation structure within our Compose application.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreenButton</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> navigator = LocalNavigator.currentOrThrow

    Button(
        onClick = {
            navigator.push(SecondScreen(<span class="hljs-string">"Hello from First Screen"</span>))
            <span class="hljs-comment">// infix call:</span>
            <span class="hljs-comment">// navigator push SecondScreen("Hello from First Screen")</span>
        }
    ) {
        Text(<span class="hljs-string">"Second Screen"</span>)
    }
}
</code></pre>
<p>We can achieve the same functionality with the <strong><em>SecondScreen</em></strong> to navigate back to the <strong><em>FirstScreen</em></strong> using the <strong><em>pop</em></strong> function. This involves calling the pop method on the navigator instance, which effectively removes the current screen from the stack and returns to the previous one.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">SecondScreenButton</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> navigator = LocalNavigator.currentOrThrow

    Button(
        onClick = {
            navigator.pop()
        }
    ) {
        Text(<span class="hljs-string">"Go Back"</span>)
    }
}
</code></pre>
<p>The last crucial step is to ensure the proper creation of the navigator to prevent any null-pointer exceptions within the composition. The flexible approach provided by <code>Voyager</code> allows us to select from a variety of default screen <a target="_blank" href="https://voyager.adriel.cafe/transitions">transitions</a>. For the purpose of this post, we will utilize the <code>SlideTransition()</code>, which offers a smooth and visually appealing way to switch between screens.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">App</span><span class="hljs-params">()</span></span> {
    MaterialTheme {
        Navigator(FirstScreen()) { navigator -&gt;
            SlideTransition(navigator)
        }
    }
}
</code></pre>
<p>The initial configuration is up and running, we can navigate between the screens and the data is preserved during the screen rotation. Let's run the project on both <strong><em>Android</em></strong> and <strong><em>iOS</em></strong> to see the results.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721975090780/11359f7c-269c-4970-ae63-2c753148c12f.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-screen-model">Screen Model</h2>
<p>It is worth mentioning that compared to the <a target="_blank" href="https://hashnode.com/post/clypbla0r000909l4gov25akn">Decompose</a> library, Voyager also has its own <code>ViewModel</code> equivalent, called the <a target="_blank" href="https://voyager.adriel.cafe/screenmodel">Screen</a><a target="_blank" href="https://voyager.adriel.cafe/navigation">Model</a>. This is an important feature to highlight because it provides a similar functionality to what many developers are already familiar with in other frameworks. However, with some recent changes in <strong>compose multiplatform</strong>, the <code>ViewModels</code> were moved to the common code. This means that you now have more flexibility in your approach and can choose the one that best fits your needs and project requirements.</p>
<p>For the sake of this post, I will use <code>ScreenModel</code> from the Voyager library. The <strong><em>ScreenModel</em></strong> is designed to store and manage UI-related data with lifecycle awareness, ensuring that your data survives configuration changes such as screen rotations. This is crucial for maintaining a consistent user experience across different device states.</p>
<p>Unlike the ViewModel, the ScreenModel is just an interface. This means that it provides a more lightweight and flexible way to manage your UI-related data. You can create a <strong><em>ScreenModel</em></strong> only from the <a target="_blank" href="https://voyager.adriel.cafe/navigation">Screen</a> component, which integrates seamlessly with the rest of the Voyager library. This integration allows you to take full advantage of Voyager's navigation and state management capabilities, making it easier to build robust and maintainable applications.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreenModel</span> : <span class="hljs-type">ScreenModel {</span></span>
    <span class="hljs-keyword">val</span> screenTitle = <span class="hljs-string">"First screen"</span>
    <span class="hljs-keyword">val</span> buttonText = <span class="hljs-string">"Second Screen"</span>
    <span class="hljs-keyword">val</span> greetings = <span class="hljs-string">"Hello from First Screen"</span>
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreen</span> : <span class="hljs-type">Screen {</span></span>

    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">val</span> screenModel = rememberScreenModel { FirstScreenModel() }
        ...
        Text(screenModel.screenTitle)
    }
}
</code></pre>
<p>Now, if we have a text input and want to store the value, we should use <strong><em>state</em></strong> inside the <strong><em>ScreenModel</em></strong>. This way, it can be retained after screen rotation.</p>
<h1 id="heading-tab-navigation">Tab Navigation</h1>
<p>To use the Tab navigation we need to add another library to our project <strong><em>voyager-tab-navigator</em></strong>.</p>
<pre><code class="lang-kotlin">[libraries]
voyager - tabs = { module = <span class="hljs-string">"cafe.adriel.voyager:voyager-tab-navigator"</span>, version.ref = <span class="hljs-string">"voyager"</span> }
</code></pre>
<pre><code class="lang-kotlin">commonMain.dependencies {
    ...
    implementation(libs.voyager.tabs)
}
</code></pre>
<p>When we want to create <strong><em>Tab</em></strong> we need to usr thr <code>Tab</code> interface instead of previously seen <code>Screen</code> interface. The idea behind tabs is the same. Nevertheless, <code>TabNavigator</code> don't support the <strong><em>backPress</em></strong> and <strong><em>Stack API</em></strong>. With the <strong><em>Tab</em></strong> interface we need to implement 2 methods:</p>
<ul>
<li><p><code>Content()</code> - the composable content of the tab</p>
</li>
<li><p><code>options()</code> - the informations about current tab <strong><em>icon</em></strong>, <strong><em>title</em></strong> and <strong><em>index</em></strong></p>
</li>
</ul>
<p>Let's create the <strong><em>FirstTab</em></strong> and implement all the methods, with some default values.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> FirstTab : Tab {
    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
        Column {
            Text(<span class="hljs-string">"First Tab"</span>)
        }
    }

    <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> options: TabOptions
        <span class="hljs-meta">@Composable</span>
        <span class="hljs-keyword">get</span>() {
            <span class="hljs-keyword">val</span> title = remember { <span class="hljs-string">"First"</span> }
            <span class="hljs-keyword">val</span> icon = rememberVectorPainter(Icons.Default.Home)

            <span class="hljs-keyword">return</span> remember {
                TabOptions(
                    index = <span class="hljs-number">0</span>u,
                    title = title,
                    icon = icon
                )
            }
        }
}
</code></pre>
<p>The <strong>SecondTab</strong> should look exactly the same but with different content.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> SecondTab : Tab {
    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
        Column {
            Text(<span class="hljs-string">"Second Tab"</span>)
        }
    }

    <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> options: TabOptions
        <span class="hljs-meta">@Composable</span>
        <span class="hljs-keyword">get</span>() {
            <span class="hljs-keyword">val</span> title = remember { <span class="hljs-string">"Second"</span> }
            <span class="hljs-keyword">val</span> icon = rememberVectorPainter(Icons.Default.AccountBox)

            <span class="hljs-keyword">return</span> remember {
                TabOptions(
                    index = <span class="hljs-number">1</span>u,
                    title = title,
                    icon = icon
                )
            }
        }
}
</code></pre>
<p>The final step involves creating a container for the tabs. To achieve this, we can follow the steps outlined at the beginning of this post and create a <strong><em>TabScreen</em></strong>. Within this screen, we will utilize the <strong><em>Scaffold</em></strong> function, which provides a basic layout structure. The <code>bottomBar</code> parameter of the <strong><em>Scaffold</em></strong> will be assigned a component called <code>BottomNavigation</code> from the Material library. This component is essential as it provides the navigation bar at the bottom of the screen, allowing users to switch between different tabs easily.</p>
<p>To ensure proper navigation and state management, the entire content should be enclosed within the <code>TabNavigator</code> function. This function is responsible for handling the navigation logic between the tabs, ensuring that the correct tab content is displayed when a user interacts with the <code>BottomNavigation</code> bar.</p>
<p>By following these steps, we can create a robust and user-friendly tabbed interface that leverages the power of Jetpack Compose and Material Design components. This setup not only provides a clean and organized layout but also ensures that the application remains responsive and intuitive for users.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TabScreen</span> : <span class="hljs-type">Screen {</span></span>
    <span class="hljs-meta">@Composable</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
        TabNavigator(FirstTab) {
            Scaffold(
                bottomBar = {
                    BottomNavigation {
                       <span class="hljs-comment">// items</span>
                    }
                }
            ) {
              <span class="hljs-comment">//Content</span>
            }
        }
    }
}
</code></pre>
<p>We can create the helper function <code>TabNavigationItem()</code> that will be using the <code>LocalTabNavigator</code> to navigate between the tabs and <code>BottomNavigationItem</code> for creating the items.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> RowScope.<span class="hljs-title">TabNavigationItem</span><span class="hljs-params">(tab: <span class="hljs-type">Tab</span>)</span></span> {
    <span class="hljs-keyword">val</span> tabNavigator = LocalTabNavigator.current

    BottomNavigationItem(
        selected = tabNavigator.current == tab,
        onClick = { tabNavigator.current = tab },
        icon = {
            tab.options.icon?.let {
                Icon(painter = it, contentDescription = tab.options.title)
            }
        }
    )
}
</code></pre>
<p>Now we can use the helper function.</p>
<pre><code class="lang-kotlin">BottomNavigation {
    TabNavigationItem(FirstTab)
    TabNavigationItem(SecondTab)
}
</code></pre>
<p>The content of our <code>Scaffold</code> function should display the current tab. To achieve this, we need to use Voyager's function <code>CurrentTab()</code>, which will dynamically render the content associated with the currently selected tab. This function ensures that the user interface updates seamlessly as users navigate between different tabs.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">()</span></span> {
    Scaffold(
        bottomBar = {
            ...
        }
    ) {
        CurrentTab()
    }
}
</code></pre>
<p>For the convenience we should add the entrypoint to any existing screen.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">TabScreenButton</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> navigator = LocalNavigator.currentOrThrow

    Button(onClick = { navigator.push(TabScreen()) }) {
        Text(<span class="hljs-string">"Tabs"</span>)
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721975231633/7540f38b-d90c-4294-bf93-efdd8dcc75cc.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-coroutines">Coroutines</h1>
<p>The <code>ScreenModel</code> offers an efficient and straightforward method to manage asynchronous operations using coroutines. By following the detailed <a target="_blank" href="https://voyager.adriel.cafe/screenmodel/coroutines-integration"><strong>documentation</strong></a>, we can impleme<a target="_blank" href="https://voyager.adriel.cafe/screenmodel/coroutines-integration">nt a countdow</a>n timer to see how this integration works in practice. The <code>Screen</code> class provides a <code>screenModelScope</code>, which is a coroutine scope that is automatically cancelled when the screen is disposed of. This ensures that any ongoing operations are properly cleaned up, preventing memory leaks and other potential issues.</p>
<p>To illustrate, let's create a simple countdown timer within the <code>ScreenModel</code>. First, we define a coroutine that will handle the countdown logic. This coroutine will decrement a timer value every second and update the UI accordingly</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreenModel</span> : <span class="hljs-type">ScreenModel {</span></span>
    ...
    <span class="hljs-keyword">val</span> countDownText = mutableStateOf&lt;String&gt;(<span class="hljs-string">"0"</span>)

    <span class="hljs-keyword">init</span> {
        screenModelScope.launch {
            <span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">10</span> downTo <span class="hljs-number">0</span>) {
                countDownText.value = i.toString()
                delay(<span class="hljs-number">1000</span>)
            }
        }
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721975596651/86afa9b9-8325-45b5-9711-79ac02a3fea2.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-summary">Summary</h1>
<p>The <code>Voyager</code> is a great library for navigation in Compose Multiplatform projects. It is easy to use and provides various ways to navigate between screens. The library is tightly coupled with <code>Jetpack Compose</code> and can use <code>ScreenModel</code> or a <code>ViewModel</code> for handling the business logic. This is really flexible and can speed up the process if you have used such an approach in the past.</p>
<p>If you are looking for a navigation library for your Compose Multiplatform project, you definitely should give it a try!</p>
<blockquote>
<p>In this series, I'll explore popular navigation libraries for Compose Multiplatform projects, starting with Voyager. Voyager offers a robust, flexible solution for managing navigation, supporting various patterns like stack-based and tab navigation. This article covers setting up Voyager, creating screens, handling navigation transitions, screen rotations, and tab navigation, and utilizing ScreenModel for state management and async operations using coroutines. By the end, you'll understand how to effectively use Voyager to navigate.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Compose Multiplatform Navigation Solutions - Decompose]]></title><description><![CDATA[Compose Multiplatform Navigation Solutions explores Kotlin and Compose Multiplatform for robust mobile app navigation strategies]]></description><link>https://michalkonkel.dev/compose-multiplatform-navigation-solutions-decompose</link><guid isPermaLink="true">https://michalkonkel.dev/compose-multiplatform-navigation-solutions-decompose</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[navigation]]></category><category><![CDATA[mobile app architecture]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[Decompose]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Mon, 10 Jun 2024 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721101424618/620a0421-8143-4d07-8ee2-8b82ea512ba1.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to another series in mobile application programming, where we will dive deep into the powerful features of Kotlin Multiplatform and Compose Multiplatform. This series aims to provide a comprehensive understanding of these technologies and how they can be leveraged to build robust mobile applications. In the upcoming posts, I will thoroughly explore several popular navigation libraries that are essential for effective app development.</p>
<p>Before starting any project, one of the critical decisions we need to make is choosing the best approach to navigation. A quick review of the available options can significantly aid in evaluating and selecting the most suitable tool for our specific needs. This series will begin with an in-depth look at <strong>Decompose</strong>, a library you might have encountered in previous posts on the <a target="_blank" href="https://hashnode.com/post/clyjngnz8000708jt58zj3tl0">Fullstack Kotlin Developer</a>.</p>
<p>Following that, we will also examine other notable libraries such as <strong>Voyager</strong>, <strong>Apyx</strong>, and <strong>Jetpack Compose</strong>. Each of these libraries offers unique features and capabilities that can enhance the navigation experience in your mobile applications.</p>
<p>To ensure a practical understanding, we will use a test application to demonstrate the functionalities of these libraries. The basic requirements for the test application are as follows:</p>
<ul>
<li><p>Application should allow us to navigate from one screen to another.</p>
</li>
<li><p>Application should allow to pass some parameters from first to second screen.</p>
</li>
<li><p>Application should handle the screen rotation without loosing data.</p>
</li>
<li><p>Application should handle the Tab Navigation.</p>
</li>
<li><p>Application should handle the async operations with coroutines.</p>
</li>
</ul>
<blockquote>
<p>The project is available in the <a target="_blank" href="https://github.com/mkonkel/DecomposeNavigation">GitHub</a> repository.</p>
</blockquote>
<hr />
<h1 id="heading-dependencies">Dependencies</h1>
<p>Base project setup, as always, is made with <a target="_blank" href="https://kmp.jetbrains.com/"><strong>Kotlin Multiplatform Wizard</strong></a>. This wizard provides a streamlined way to create a multiplatform project, ensuring that we have a solid foundation to build upon. We also need to add some <a target="_blank" href="https://arkivanov.github.io/Decompose/getting-started/installation/#__tabbed_1_2">Decompose</a> as it is the core thing that we would like to examine. There is also one thing that we need to add to the project, and that is the <a target="_blank" href="https://github.com/Kotlin/kotlinx.serialization">Kotlin Serialization</a> plugin.</p>
<p><code>libs.versions.toml</code></p>
<pre><code class="lang-kotlin">[versions]
decompose = <span class="hljs-string">"3.0.0-beta01"</span>
serialization = <span class="hljs-string">"1.6.3"</span>

[libraries]
decompose = { module = <span class="hljs-string">"com.arkivanov.decompose:decompose"</span>, version.ref = <span class="hljs-string">"decompose"</span> }
decompose-compose = { module = <span class="hljs-string">"com.arkivanov.decompose:extensions-compose"</span>, version.ref = <span class="hljs-string">"decompose"</span> }
serialization-json = { module = <span class="hljs-string">"org.jetbrains.kotlinx:kotlinx-serialization-json"</span>, version.ref = <span class="hljs-string">"serialization"</span> }

[plugins]
kotlinSerialization = { id = <span class="hljs-string">"org.jetbrains.kotlin.plugin.serialization"</span>, version.ref = <span class="hljs-string">"kotlin"</span> }
</code></pre>
<p>Freshly added dependencies needs to be synced with the project and added to the build file.</p>
<p><code>build.gradle.kts</code></p>
<pre><code class="lang-kotlin">plugins {
    alias(libs.plugins.kotlinSerialization)
}

sourceSets {
    androidMain.dependencies {
        ...
        implementation(libs.decompose)
    }
    commonMain.dependencies {
        ...
        implementation(libs.decompose)
        implementation(libs.decompose.compose)
        implementation(libs.serialization)
    }
}
</code></pre>
<p>Now we can sync the project and start coding.</p>
<h1 id="heading-decompose-introduction">Decompose Introduction</h1>
<p>Following the <strong>Decompose</strong> documentation, we can see that the main element of the library is the <a target="_blank" href="https://arkivanov.github.io/Decompose/component/overview/">Component</a> class. This class encapsulates logic and can contain other components, making it a powerful tool for managing complex applications.</p>
<h2 id="heading-components">Components</h2>
<p>Components are lifecycle-aware, which means their <a target="_blank" href="https://arkivanov.github.io/Decompose/component/overview/">lifecycle</a> is automatically managed by the framework. This lifecycle management is very similar to Android’s activity lifecycle, providing a familiar structure for Android developers.</p>
<p>One of the key features of components is that they are independent of the UI. This separation ensures that the UI relies on the components, allowing for a clean architecture where the business logic is kept separate from the presentation layer. The idea is to hold as much code in the shared logic as possible, making the application more modular and easier to maintain.</p>
<p>Components are responsible for holding business logic and managing navigation. The navigation logic is also separated from the UI, which further enforces the separation of concerns. If you are familiar with Android development, you can think of the components as analogous to the ViewModel. This similarity makes it easier for developers to transition to using Decompose.</p>
<p>By following these principles, we can create a robust and maintainable application architecture that leverages the full power of the Decompose library.</p>
<p>Each component should have a <code>ComponentContext</code> that manages its lifecycle, keeps its state (can preserve component state during changes), and handles the back button. The context is passed through the constructor and can be added to the component by delegation.</p>
<p>Because of that, the main point of the app should be a <code>RootComponent</code>, which should be provided with the <code>ComponentContext</code> to determine how it should act on different platforms. Therefore, its context must be created on the platform side itself. For such situations, we can use the <code>DefaultComponentContext()</code>. If we are working on Android, it should be created inside the <strong><em>Composable</em></strong> function, and we should always use the <code>remember()</code> function so the context will not be recreated with every recomposition.</p>
<p>With that covered, we can start to code. Let's create a <em>navigation</em> package in our project with the <strong>RootComponent</strong>. The <strong>RootComponent</strong> will live as long as the application.</p>
<p><img src="https://speednetsoftware.com/app/uploads/2024/06/1_basic_project_structure-1-480x0-c-default.png" alt class="image--center mx-auto" /></p>
<p><code>RootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RootComponent</span></span>(
    componentContext: ComponentContext
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-comment">// Some code here</span>
}
</code></pre>
<h3 id="heading-configuration">Configuration</h3>
<p>Let’s assume that our application will have two screens: <code>FirstScreen</code> and <code>SecondScreen</code>. Both screens will be represented by the <code>Component</code> class. The <code>FirstScreen</code> will be the initial screen shown to the user, and the <code>SecondScreen</code> will appear after the user clicks a button on the <code>FirstScreen</code>. To manage this navigation, we need to create a <a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/overview/"><strong>Stack</strong></a> within the <code>RootComponent</code>. This stack is provided to the component through the <code>ComponentContext</code>.</p>
<p>To set up the stack, we need to define a <code>Configuration</code> class. This class must be <code>@Serializable</code> because it will represent the child components and contain all the necessary arguments to create them. The <code>Configuration</code> class will help us manage the state and lifecycle of each screen, ensuring that the correct screen is displayed based on user interactions.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Configuration</span> </span>{
    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> FirstScreen : Configuration()

    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecondScreen</span></span>(<span class="hljs-keyword">val</span> text: String) : Configuration()
}
</code></pre>
<h3 id="heading-stack-navigation">Stack Navigation</h3>
<p>The created configuration can now be used to set up the stack, which will manage the navigation between our screens. To achieve this, we should utilize the <a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/stack/navigation/"><strong>StackNavigator</strong>interface.</a> Th<a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/stack/navigation/">i</a>s interface provides a comprehensive set of methods that are essential for handling the navigation process effectively.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> navigation = StackNavigation&lt;Configuration&gt;()
</code></pre>
<p>The definitions of child components are created by the <strong>Configuration</strong>, but now they also need to create <a target="_blank" href="https://arkivanov.github.io/Decompose/component/child-components/">Child Components</a> themselves. Components are organized as trees, where the root component is the main component, and the child components are created by the main component. The parent component only knows about its direct children, ensuring a clear hierarchy and separation of concerns.</p>
<p>Each component can be independently reused anywhere in the app, making the architecture flexible and modular. With the use of navigation, components are automatically created and destroyed as needed. They require a provided component context from the parent to function correctly and handle their lifecycle.</p>
<p>Let’s now focus on linear navigation using the <a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/stack/overview/">Child Stack</a> approach. This method allows us to manage a stack of child configurations, where each configuration represents a screen in the navigation stack. When a new screen is pushed onto the stack, it becomes the active screen, and when a screen is popped, the previous screen is reactivated. This approach is particularly useful for scenarios where you need to navigate back and forth between screens, maintaining the state and lifecycle of each screen appropriately.</p>
<p>You can find other navigation approaches in the documentation, which might be more suitable depending on the specific requirements of your application.</p>
<p>During the navigation, the child stack compares new configurations with the previous one. There should be only one (the top) component active, others are in the back and stopped or destroyed.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreenComponent</span></span>(
    componentContext: ComponentContext
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-comment">// Some code here</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecondScreenComponent</span></span>(
    componentContext: ComponentContext,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> text: String
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-comment">// Some code here</span>
}
</code></pre>
<h3 id="heading-rootcomponent">RootComponent</h3>
<p>With new components added, we now need to create them inside the root component – they are called children.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> </span>{
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreen</span></span>(<span class="hljs-keyword">val</span> component: FirstScreenComponent) : Child()
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecondScreen</span></span>(<span class="hljs-keyword">val</span> component: SecondScreenComponent) : Child()
}
</code></pre>
<p>The last thing to do for working navigation is to create the <code>childStack</code>. The <code>childStack</code> requires some parameters to be passed, such as the source of the navigation, the serializer, the initial configuration, the handleBackButton, and the childFactory. The <code>childFactory</code> is a function that creates the child component based on the configuration and component context. The childStack is responsible for creating the child components and managing their lifecycle.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> childStack = childStack(
   source = navigation,
   serializer = Configuration.serializer(),
   initialConfiguration = Configuration.FirstScreen,
   handleBackButton = <span class="hljs-literal">true</span>,
   childFactory = ::createChild
)
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createChild</span><span class="hljs-params">(configuration: <span class="hljs-type">Configuration</span>, componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: Child =
   <span class="hljs-keyword">when</span> (configuration) {
      <span class="hljs-keyword">is</span> Configuration.FirstScreen -&gt; Child.FirstScreen(FirstScreenComponent(componentContext))
      <span class="hljs-keyword">is</span> Configuration.SecondScreen -&gt; Child.SecondScreen(SecondScreenComponent(componentContext, configuration.text))
   }
</code></pre>
<p><code>ChildStack</code> cannot be empty; it must always have at least one active (resumed) child component. Components that are not active are always in a stopped state. If we want to use multiple <code>ChildStacks</code> within a single component, each <code>ChildStack</code> must have a unique key associated with it to distinguish them.</p>
<p>When we examine the <code>childStack</code> function, we can see that it returns a <a target="_blank" href="https://github.com/arkivanov/Decompose/tree/master/decompose/src/commonMain/kotlin/com/arkivanov/decompose/value">Value</a> type. This <code>Value</code> type is crucial because it represents the current state of the <code>ChildStack</code>, including the active child component and any components that are in the back stack. The <code>Value</code> type allows us to observe changes to the <code>ChildStack</code> and react accordingly.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">val</span> childStack: Value&lt;ChildStack&lt;RootComponent.Configuration, RootComponent.Child&gt;&gt;
</code></pre>
<p>The <code>Value</code> is a type that represents a value that can be observed as the Decompose equivalent of Jetpack Compose <code>State</code>. It is also independent of the approach you want to use further in the application. Nevertheless, in the <strong><em>Compose Multiplatform</em></strong> approach, it can (and should) be transformed to the state.</p>
<h1 id="heading-handling-the-linear-navigation">Handling the Linear Navigation</h1>
<p>With everything done, we can now handle the actual navigation. Following the <a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/stack/overview/#delivering-a-result-when-navigating-back">documentation</a>, we can handle it in multiple ways – with traditional callbacks or with a more reactive approach using <code>flow</code> or <code>observable</code>. It’s up to you how you want to communicate child components with the root component. You can also create a global <strong><em>navigation</em></strong> object that will be responsible for changing the screens from any place in the app. There is no good or bad practice. For simplicity, I will use the callbacks.</p>
<h2 id="heading-adjusting-components">Adjusting components</h2>
<p>In the <code>firstScreen</code>, I will add a lambda expression on <code>onButtonClick: (String) -&gt; Unit</code> that will be called when the button is clicked. The lambda will be called with the greetings text, and handled in the <code>RootComponent</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreenComponent</span></span>(
    componentContext: ComponentContext,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onButtonClick: (String) -&gt; <span class="hljs-built_in">Unit</span>,
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">click</span><span class="hljs-params">()</span></span> {
        onButtonClick(<span class="hljs-string">"Hello from FirstScreenComponent!"</span>)
    }
}
</code></pre>
<p>Now we need to implement the callback and handle the navigation.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@OptIn(ExperimentalDecomposeApi::class)</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createChild</span><span class="hljs-params">(configuration: <span class="hljs-type">Configuration</span>, componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: Child =
    <span class="hljs-keyword">when</span> (configuration) {
        <span class="hljs-keyword">is</span> Configuration.FirstScreen -&gt; {
            Child.FirstScreen(
                component = FirstScreenComponent(
                    componentContext = componentContext,
                    onButtonClick = { textFromFirstScreen -&gt;
                        navigation.pushNew(Configuration.SecondScreen(text = textFromFirstScreen))
                    }
                )
            )
        }
            ...
    }
</code></pre>
<p>The <strong><em>Decompose</em></strong> gives plenty wat of starting new screens:</p>
<ul>
<li><p><code>push(configuration)</code> – pushes new screen to top of the stack</p>
</li>
<li><p><code>pushNew(configuration)</code> – pushes new screen to top of the stack, does nothing if configuration already on the top of stack</p>
</li>
<li><p><code>pushToFront(configuration)</code> – pushes the provided configuration to the top of the stack, removing the configuration from the back stack, if any</p>
</li>
<li><p><code>pop()</code> – pops the latest configuration at the top of the stack.</p>
</li>
<li><p>and more, that are described <a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/stack/navigation/#stacknavigator-extension-functions">here</a></p>
</li>
</ul>
<p>The same approach can be used to handle the back button. The <code>handleBackButton</code> parameter in the <code>childStack</code> is responsible for that. If the back button is pressed, the <code>childStack</code> will pop the latest configuration from the stack.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecondScreenComponent</span></span>(
    componentContext: ComponentContext,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> text: String,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onBackButtonClick: () -&gt; <span class="hljs-built_in">Unit</span>
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getGreeting</span><span class="hljs-params">()</span></span>: String = text
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">goBack</span><span class="hljs-params">()</span></span> {
        onBackButtonClick()
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@OptIn(ExperimentalDecomposeApi::class)</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createChild</span><span class="hljs-params">(configuration: <span class="hljs-type">Configuration</span>, componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: Child =
    <span class="hljs-keyword">when</span> (configuration) {
            ...
        <span class="hljs-keyword">is</span> Configuration.SecondScreen -&gt; Child.SecondScreen(
            component = SecondScreenComponent(
                componentContext = componentContext,
                text = configuration.text,
                onBackButtonClick = { navigation.pop() }
            )
        )
    }
</code></pre>
<h2 id="heading-adding-the-common-ui">Adding the common UI</h2>
<p>The navigation is now complete, and it is independent of the UI. It’s pure Kotlin, placed in shared code, and it can be unit-tested. The last thing to do is to create the UI for the screens. It will be as simple as possible, a column with texts and buttons. Each screen will be a <code>@Composable</code> function that takes a <strong><em>component</em></strong> as a parameter.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FirstScreen</span><span class="hljs-params">(
    component: <span class="hljs-type">FirstScreenComponent</span>
)</span></span> {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(<span class="hljs-string">"First screen"</span>)
        Button(onClick = { component.click() }) {
            Text(<span class="hljs-string">"Second Screen"</span>)
        }
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">SecondScreen</span><span class="hljs-params">(
    component: <span class="hljs-type">SecondScreenComponent</span>
)</span></span> {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(<span class="hljs-string">"First screen"</span>)
        Spacer(modifier = Modifier.height(<span class="hljs-number">16</span>.dp))
        Text(<span class="hljs-string">"Greetings: <span class="hljs-subst">${component.getGreeting()}</span>"</span>)
        Button(onClick = { component.goBack() }) {
            Text(<span class="hljs-string">"Go Back"</span>)
        }
    }
}
</code></pre>
<p>The buttons are invoking functions that are provided via the components. As we remember functions will trigger the navigation in our <code>rootComponent</code>.</p>
<h2 id="heading-entrypoints">Entrypoints</h2>
<p>The entrypoint to our application is the <code>App()</code> function where will take the <code>RootComponent</code> as a parameter and handle the navigation events from the <code>childStack</code>. Each platform <strong><em>iOS</em></strong> and <strong><em>Android</em></strong> will create the <strong><em>rootComponent</em></strong> and pass it to the function.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> childStack = rootComponent.childStack.subscribeAsState()
</code></pre>
<p>The decompose <code>Value</code> can be transformed to the <code>State</code> by the <code>subscribeAsState()</code> function. To handle upcoming changes in the stack, the library provides a special composable function called <code>Children</code> that takes the stack as a parameter and can be configured using standard modifiers. It also can use different types of transition animations with the <code>StackAnimation</code>. The last parameter of the <code>Children</code> function is a lambda expression that will be called with every new child on the top of the stack. This is where we can specify how to display new components.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">App</span><span class="hljs-params">(rootComponent: <span class="hljs-type">RootComponent</span>)</span></span> {
    MaterialTheme {
        <span class="hljs-keyword">val</span> childStack = rootComponent.childStack.subscribeAsState()
        Children(
            stack = childStack.value,
            animation = stackAnimation(slide()),
        ) { child -&gt;
            <span class="hljs-keyword">when</span> (<span class="hljs-keyword">val</span> instance = child.instance) {
                <span class="hljs-keyword">is</span> RootComponent.Child.FirstScreen -&gt;
                    FirstScreen(instance.component)

                <span class="hljs-keyword">is</span> RootComponent.Child.SecondScreen -&gt;
                    SecondScreen(instance.component)
            }
        }
    }
}
</code></pre>
<p>The last thing to do is to create the <code>RootComponent</code> in the platform-specific code. Next pass it to the <code>App()</code> function. For Android, it will be the <code>MainActivity</code> located in the <code>androidMain</code>, and for iOS the <code>MainViewController</code> located in <code>iosMain</code>.</p>
<h3 id="heading-android">Android</h3>
<p>For Android we should use the decomposes <code>retainedComponent()</code> function that will create the <code>RootComponent</code> and retain it during the configuration changes. It also creates the <code>componentContex</code> out of the box.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">ComponentActivity</span></span>() {
    <span class="hljs-meta">@OptIn(ExperimentalDecomposeApi::class)</span>
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)

        <span class="hljs-keyword">val</span> rootComponent = retainedComponent { componentContext -&gt;
            RootComponent(
                componentContext = componentContext
            )
        }
        setContent {
            App(rootComponent = rootComponent)
        }
    }
}
</code></pre>
<h3 id="heading-ios">iOS</h3>
<p>Since the <strong>iOS</strong> entry point is a composable function, we will need to create <code>componentContext</code> ourselves. Thankfully, Decompose has the proper functions for it. I will use the <code>DefaultComponentContext()</code> that takes the <code>Lifecycle</code> as a parameter, which is also created by part of the Decompose library via the <code>LifecycleRegistry()</code>. To prevent creating new components on each recomposition, we should <code>remember</code> the instantiated component.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">MainViewController</span><span class="hljs-params">()</span></span> = ComposeUIViewController {
    <span class="hljs-keyword">val</span> rootComponent = remember {
        RootComponent(
            componentContext = DefaultComponentContext(LifecycleRegistry())
        )
    }

    App(rootComponent)
}
</code></pre>
<p>That’s all! We can now run the application on both Android and iOS devices and expect the same behavior! How exciting is that?!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721187467006/e9a66389-42a1-4c43-bb40-255e5749a233.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-handling-the-tab-navigation">Handling the Tab Navigation</h1>
<p>To test the library further, we can now add <strong><em>Tab Navigation</em></strong> to the App. This will allow us to switch between different sections of the app easily. Let's start by creating a new screen that will have its own <code>childStack</code> and an entry point on the <code>firstScreen</code>. The steps we need to follow are similar to what we did before. However, there will be some differences in how we handle the creation and navigation of child components in this new setup.</p>
<p>The <code>TabNavigationScreen</code> will behave in almost the same way as the <code>RootComponent</code>. It will have its own <code>childStack</code>, <code>configuration</code>, and <code>childFactory</code>, and will be responsible for creating the child components and navigating between them.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> </span>{
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TabOne</span></span>(<span class="hljs-keyword">val</span> component: ThirdScreenComponent) : Child()
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TabTwo</span></span>(<span class="hljs-keyword">val</span> component: FourthScreenComponent) : Child()
}

<span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Configuration</span> </span>{
    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> TabOne : Configuration()

    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> TabTwo : Configuration()
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThirdScreenComponent</span></span>(
    componentContext: ComponentContext,
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-keyword">val</span> text = <span class="hljs-string">"Hello from ThirdScreen"</span>
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FourthScreenComponent</span></span>(
    componentContext: ComponentContext,
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-keyword">val</span> text = <span class="hljs-string">"Hello from FourthScreen"</span>
}
</code></pre>
<p>We need to remember that each <code>stack</code> within our application should have its own unique key. This is crucial because these keys help in identifying and managing the different navigation stacks independently. When we create a new screen with its own childStack, we must ensure that the keys assigned to these stacks do not overlap with others.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> navigation = StackNavigation&lt;TabNavigationComponent.Configuration&gt;()

<span class="hljs-keyword">val</span> childStack = childStack(
    source = navigation,
    serializer = navigation.tab.TabNavigationComponent.Configuration.serializer(),
    initialConfiguration = navigation.tab.TabNavigationComponent.Configuration.TabOne,
    handleBackButton = <span class="hljs-literal">true</span>,
    childFactory = ::createChild,
    key = <span class="hljs-string">"TabNavigationStack"</span>
)

<span class="hljs-meta">@OptIn(ExperimentalDecomposeApi::class)</span>
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createChild</span><span class="hljs-params">(
    configuration: <span class="hljs-type">TabNavigationComponent</span>.<span class="hljs-type">Configuration</span>,
    componentContext: <span class="hljs-type">ComponentContext</span>
)</span></span>: TabNavigationComponent.Child =
    <span class="hljs-keyword">when</span> (configuration) {
        <span class="hljs-keyword">is</span> TabNavigationComponent.Configuration.TabOne -&gt; {
            TabNavigationComponent.Child.TabOne(ThirdScreenComponent(componentContext))
        }

        <span class="hljs-keyword">is</span> TabNavigationComponent.Configuration.TabTwo -&gt; {
            TabNavigationComponent.Child.TabTwo(FourthScreenComponent(componentContext))
        }
    }
</code></pre>
<p>The <code>TabNavigationComponent</code> is responsible for managing tab clicks within the application. To achieve this, we will use the <a target="_blank" href="https://arkivanov.github.io/Decompose/navigation/stack/navigation/#bringtofrontconfiguration-configuration"><strong>bringToFront</strong></a> function. This function is essential for ensuring that the selected tab is brought to the forefront of the user interface, providing a seamless and intuitive navigation experience.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onTabOneClick</span><span class="hljs-params">()</span></span> {
    navigation.bringToFront(Configuration.TabOne)
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onTabTwoClick</span><span class="hljs-params">()</span></span> {
    navigation.bringToFront(Configuration.TabTwo)
}
</code></pre>
<p>The last thing to do in the <strong>components</strong> is to provide a way to run the <code>TabNavigationScreen</code> from the <code>FirstScreen</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FirstScreenComponent</span></span>(
    componentContext: ComponentContext,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onGoToSecondScreenClick: (String) -&gt; <span class="hljs-built_in">Unit</span>,
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onGoToTabsScreen: () -&gt; <span class="hljs-built_in">Unit</span>,
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">newScreen</span><span class="hljs-params">()</span></span> {
        onGoToSecondScreenClick(<span class="hljs-string">"Hello from FirstScreenComponent!"</span>)
    }

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">tabScreen</span><span class="hljs-params">()</span></span> {
        onGoToTabsScreen()
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RootComponent</span></span>(...) {

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createChild</span><span class="hljs-params">(...)</span></span> {
        <span class="hljs-keyword">when</span> (configuration) {
            <span class="hljs-keyword">is</span> Configuration.FirstScreen -&gt; Child.FirstScreen(
                component = FirstScreenComponent(
                    onGoToTabsScreen = {
                        navigation.pushNew(Configuration.TabsNavigation)
                    }
                )
            )
                ...
                Configuration.TabsNavigation
            -&gt; Child.TabsScreen(
                component = TabNavigationComponent(
                    componentContext = componentContext
                )
            )
        }
    }

    <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> </span>{
        ...
        <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TabsScreen</span></span>(<span class="hljs-keyword">val</span> component: TabNavigationComponent) : Child()
    }

    <span class="hljs-meta">@Serializable</span>
    <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Configuration</span> </span>{
        ...
        <span class="hljs-meta">@Serializable</span>
        <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> TabsNavigation : Configuration()
    }
}
</code></pre>
<p>The final step involves managing the changes on the UI layer to ensure that the user interface responds appropriately to the navigation events and state changes. This includes updating the UI components to reflect the current screen and handling any transitions between screens smoothly.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">App</span><span class="hljs-params">(...)</span></span> {
    ...
    Children() { child -&gt;
        ...
        <span class="hljs-keyword">is</span> RootComponent.Child.TabsScreen -&gt;
        TabsScreen(instance.component)
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">TabsScreen</span><span class="hljs-params">(
    tabNavigationComponent: <span class="hljs-type">TabNavigationComponent</span>
)</span></span> {
    Scaffold(
        bottomBar = {
            Row(
                horizontalArrangement = Arrangement.Center
            ) {
                Button(onClick = { tabNavigationComponent.onTabOneClick() }) {
                    Text(<span class="hljs-string">"TAB ONE"</span>)
                }
                Button(onClick = { tabNavigationComponent.onTabTwoClick() }) {
                    Text(<span class="hljs-string">"TAB TWO"</span>)
                }
            }
        }
    ) { innerPadding -&gt;
        <span class="hljs-keyword">val</span> childStack = tabNavigationComponent.childStack.subscribeAsState()

        Column(
            modifier = Modifier.padding(innerPadding),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Children(
                stack = childStack.value,
                animation = stackAnimation(slide()),
            ) { child -&gt;
                <span class="hljs-keyword">when</span> (<span class="hljs-keyword">val</span> instance = child.instance) {
                    <span class="hljs-keyword">is</span> TabNavigationComponent.Child.TabOne -&gt;
                        ThirdScreen(instance.component)

                    <span class="hljs-keyword">is</span> TabNavigationComponent.Child.TabTwo -&gt;
                        FourthScreen(instance.component)
                }
            }
        }
    }
}
</code></pre>
<blockquote>
<p>If you want, you can use the BottomNavigation control from Jetpack Compose to handle the bottom bar. This will help you manage the state, for example, allowing you to slightly change the color of the selected tab and more...</p>
</blockquote>
<p><code>ThirdScreen</code> and <code>FourthScreen</code> are similar to the previous screens in terms of simplicity and functionality</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">ThirdScreen</span><span class="hljs-params">(
    component: <span class="hljs-type">ThirdScreenComponent</span>
)</span></span> {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(component.text)
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721188507016/0a7f7688-e217-4f84-9586-9fa38fdb0311.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-coroutine-support">Coroutine support</h1>
<p>Since every modern mobile application should be reactive and handle asynchronous operations, we can leverage coroutines to achieve this. To implement coroutines in our component, we need to create a <code>CoroutineScope</code>. Unlike the native <strong><em>ViewModel</em></strong>, which provides coroutine support out-of-the-box. WIth <strong>Decompose</strong> such approach requires a bit more setup but is still straightforward to manage.</p>
<p>First, we define a <code>CoroutineScope</code> within our component. This scope will allow us to launch and manage coroutines effectively. The <code>Component</code> is lifecycle-aware, which means it can automatically handle the cleanup of coroutines when the component is destroyed. This lifecycle awareness is crucial because it helps prevent memory leaks and ensures that coroutines do not continue running after the component is no longer in use.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThirdScreenComponent</span></span>(
    componentContext: ComponentContext,
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-keyword">val</span> text = <span class="hljs-string">"Hello from ThirdScreen"</span>
    <span class="hljs-keyword">val</span> countDownText = mutableStateOf&lt;String&gt;(<span class="hljs-string">"0"</span>)

    <span class="hljs-keyword">init</span> {
        <span class="hljs-keyword">val</span> scope = coroutineScope(Dispatchers.Default + SupervisorJob())
        scope.launch {
            <span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">10</span> downTo <span class="hljs-number">0</span>) {
                countDownText.value = i.toString()
                delay(<span class="hljs-number">1000</span>)
            }
        }
    }


    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">CoroutineScope</span><span class="hljs-params">(context: <span class="hljs-type">CoroutineContext</span>, lifecycle: <span class="hljs-type">Lifecycle</span>)</span></span>: CoroutineScope {
        <span class="hljs-keyword">val</span> scope = CoroutineScope(context)
        lifecycle.doOnDestroy(scope::cancel)
        <span class="hljs-keyword">return</span> scope
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> LifecycleOwner.<span class="hljs-title">coroutineScope</span><span class="hljs-params">(context: <span class="hljs-type">CoroutineContext</span>)</span></span>: CoroutineScope =
        CoroutineScope(context, lifecycle)
}
</code></pre>
<p>Or you can use the Decompose compatibility library, which provides the <code>coroutineScope</code> function to handle the lifecycle for you – <a target="_blank" href="https://github.com/arkivanov/Essenty">Essenty</a>.</p>
<pre><code class="lang-kotlin">versions]
essently = <span class="hljs-string">"2.0.0"</span>

[libraries]
essently - coroutines = { module = <span class="hljs-string">"com.arkivanov.essenty:lifecycle-coroutines"</span>, version.ref = <span class="hljs-string">"essently"</span> }
</code></pre>
<pre><code class="lang-kotlin">commonMain.dependencies {
    ...
    implementation(libs.essently.coroutines)
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FourthScreenComponent</span></span>(
    componentContext: ComponentContext,
) : ComponentContext <span class="hljs-keyword">by</span> componentContext {
    <span class="hljs-keyword">val</span> text = <span class="hljs-string">"Hello from FourthScreen"</span>
    <span class="hljs-keyword">val</span> countDownText = mutableStateOf&lt;String&gt;(<span class="hljs-string">"0"</span>)

    <span class="hljs-comment">//Essently</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> scope = coroutineScope(Dispatchers.Default + SupervisorJob())

    <span class="hljs-keyword">init</span> {
        scope.launch {
            <span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">10</span> downTo <span class="hljs-number">0</span>) {
                countDownText.value = i.toString()
                delay(<span class="hljs-number">1000</span>)
            }
        }
    }
}
</code></pre>
<p>If u want to support structured concurrency you should pass the <code>mainContext: CoroutineContext</code> to the component instead of using <code>Dispatchers.Default</code> inside it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721188815179/01f896b0-d944-4718-821a-5f259b0d5d91.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-sumary">Sumary</h1>
<p>The <code>Decompose</code> library is a powerful tool for composing multiplatform applications that support <strong>Android</strong>, <strong>iOS</strong>, <strong>WEB</strong>, and <strong>Desktop</strong>. It separates the UI code and handles it with common shared logic. It’s straightforward, easy to use, and can be customized to fit your needs. However, it is strongly tied to the library’s internal concepts, such as <code>Components</code>, which force you to design the app in a specific way and limit possibilities. In my view, the biggest advantage of this approach is the clear boundary between UI and Navigation. Navigation becomes part of your business logic, not just the way you build your views, and can be easily tested and reused.</p>
<p>To sum things up, <code>Decompose</code> is a great library that can be used to <strong>compose multiplatform projects</strong>, and the approach proposed by the creators of the library suits me well. It is a great way to separate the navigation from the UI. If you are looking for a navigation library for your compose multiplatform project, you definitely should give it a try!</p>
<p>If you are interested in how it works in a bit bigger application, take a look at my <a target="_blank" href="https://github.com/mkonkel/GameShop">GitHub</a> for the <code>GameShop</code> application.</p>
<blockquote>
<p>This series explores Kotlin Multiplatform and Compose Multiplatform, focusing on navigation libraries to enhance mobile application development. Starting with an in-depth look at Decompose, we cover setting up a test application, handling lifecycle, navigation, and async operations using coroutines. This approach separates navigation from UI, providing a modular and testable architecture. Subsequent posts will examine Voyager, Apyx and JetpackCompose Navigation, comparing their features and suitability. Check the GitHub repository for a practical example.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Complete Guide to Becoming a Fullstack Kotlin Developer - UI with Compose Multiplatform]]></title><description><![CDATA[Comprehensive guide on building a fullstack Kotlin application with Compose Multiplatform, supporting Android, iOS, and Web with shared codebase]]></description><link>https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-ui-with-compose-multiplatform</link><guid isPermaLink="true">https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-ui-with-compose-multiplatform</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Mobile apps]]></category><category><![CDATA[Android]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[fullstack]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Mon, 20 May 2024 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721041362319/7b7d7fc7-e7dd-420e-ae5f-08175e99e7cd.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In previous <a target="_blank" href="https://hashnode.com/post/clymugiht000509jt0onuej9d">posts</a>, I’ve created the repository and presentation layers of the applications. Now, the time has come for the <strong>UI</strong> layer. The interaction points are where the user can finally use the application. The most significant benefit of using <strong>Compose Multiplatform</strong> is that we can use the same UI on all platforms. The once-created UI will be used on Android, iOS, and Web without any problem.</p>
<blockquote>
<p><em>The complete project is avaiable on</em><a target="_blank" href="https://github.com/mkonkel/GameShop"><em>GitHub</em></a></p>
</blockquote>
<hr />
<h1 id="heading-dependencies">Dependencies</h1>
<blockquote>
<p>We should use the latest <a target="_blank" href="https://github.com/JetBrains/compose-multiplatform/releases">Compose Multiplatform</a> release (at the time of writing this article, the current version was 1.6.0-rc03).</p>
</blockquote>
<p><code>gradle/libs.versions.toml</code></p>
<pre><code class="lang-kotlin">compose-plugin = <span class="hljs-string">"1.6.0-rc03"</span> 
... 
jetbrainsCompose = { id = <span class="hljs-string">"org.jetbrains.compose"</span>, version.ref = <span class="hljs-string">"compose-plugin"</span> }
</code></pre>
<h1 id="heading-screen-model">Screen model</h1>
<p>One of the first things that need to be implemented is a <strong>model</strong> for our screen. In my approach, this will be a set of essential elements like text, input field, button, image, and more. Each will have its representation in <strong>shared</strong> code and be resolved to the UI control in the <strong>compose</strong> module.</p>
<p>Suppose we are thinking about the <strong>login</strong> screen. In that case, we can imagine that it should have an input for an email and an input for a password (which should be secured), a button enabling us to call the API request, and a button that can change the screen from login to register if we are a new user.</p>
<p>Let’s start with the model and some controls.</p>
<p><code>shared/commonMain/features/login/LoginModel.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginModel</span></span>( 
    <span class="hljs-keyword">val</span> login: InputText, 
    <span class="hljs-keyword">val</span> pass: InputText, 
    <span class="hljs-keyword">val</span> loginButton: Button, 
    <span class="hljs-keyword">val</span> registerButton: Button, 
)
</code></pre>
<p><code>shared/commonMain/widget/input/InputTetx.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InputText</span></span>( 
    <span class="hljs-keyword">val</span> text: MutableState&lt;String&gt; = mutableStateOf(<span class="hljs-string">""</span>), 
    <span class="hljs-keyword">val</span> label: String = <span class="hljs-string">""</span>, 
    <span class="hljs-keyword">val</span> maxLines: <span class="hljs-built_in">Int</span> = <span class="hljs-number">1</span>, 
    <span class="hljs-keyword">val</span> type: Type = Type.NORMAL, 
) { 
    <span class="hljs-keyword">enum</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Type</span> </span>{ 
        NORMAL, 
        SECURE, 
    } 
}
</code></pre>
<p>Since we are developing a compose multiplatform application, we can easily benefit from the compose <code>mutableStateOf</code> – in the case of <code>InputField</code>, we can use it to hold the current user’s input and use it later in the business logic</p>
<h1 id="heading-control-widgets">Control Widgets</h1>
<p>With the provided <code>mutableState</code>, we can use it as the current value of the text and then update it on every value that has changed. Using the remember lambda will ensure that the produced value remains the same during the layout recomposition. The UI representation of the input model may look like this:</p>
<p><code>composeApp/commonMain/ui/widget/Input.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-function"><span class="hljs-keyword">fun</span> InputText.<span class="hljs-title">Widget</span><span class="hljs-params">( 
    modifier: <span class="hljs-type">Modifier</span> = Modifier, 
)</span></span> { 
    <span class="hljs-keyword">var</span> currentText <span class="hljs-keyword">by</span> remember { text } 

    Column { 
        OutlinedTextField( 
            value = currentText, 
            onValueChange = { 
                currentText = it 
            }, 
            modifier = Modifier.then(modifier), 
            label = { 
                Text(label) 
            }, 
            singleLine = maxLines == <span class="hljs-number">1</span>, 
            maxLines = maxLines, 
            visualTransformation = 
                <span class="hljs-keyword">if</span> (type == InputText.Type.SECURE) { 
                    PasswordVisualTransformation() 
                } <span class="hljs-keyword">else</span> { 
                    VisualTransformation.None 
                }, 
        ) 
    } 
}
</code></pre>
<p>The button model should be straightforward; we can define an enum class responsible for the styling.</p>
<p><code>composeApp/commonMain/ui/widget/Button.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-function"><span class="hljs-keyword">fun</span> AppButton.<span class="hljs-title">Widget</span><span class="hljs-params">(modifier: <span class="hljs-type">Modifier</span> = Modifier)</span></span> { 
    <span class="hljs-keyword">when</span> (<span class="hljs-keyword">this</span>.style) { 
        FILLED -&gt; { 
            Button(modifier = modifier, onClick = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.onClick) { 
                Text(text = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.text) 
            } 
        } 
        OUTLINED -&gt; { 
            OutlinedButton(modifier = modifier, onClick = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.onClick) { 
                Text(text = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.text) 
            } 
        } 

        TEXT -&gt; { 
            TextButton(modifier = modifier, onClick = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.onClick) { 
                Text(text = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.text) 
            } 
        } 

        FLOATING -&gt; 
            ExtendedFloatingActionButton( 
                modifier = modifier, 
                onClick = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.onClick, 
            ) { 
                Text(text = <span class="hljs-keyword">this</span><span class="hljs-symbol">@Widget</span>.text) 
            } 
    } 
}
</code></pre>
<h1 id="heading-screen-component">Screen Component</h1>
<p>The last thing to do is to provide this mode via the <code>LoginComponent</code> and handle it in the <code>LoginScreen</code>.</p>
<p><code>shared/commonMain/features/login/LoginComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">LoginComponent</span> </span>{ 
    <span class="hljs-keyword">val</span> model: LoginModel 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onLoginClick</span><span class="hljs-params">()</span></span> 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onRegisterClick</span><span class="hljs-params">()</span></span> 
}
</code></pre>
<p><code>shared/commonMain/features/login/RealLoginComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealLoginComponent</span></span>( 
    componentContext: ComponentContext, 
    coroutineContext: CoroutineContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> loginRepository: LoginRepository, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onLogin: () -&gt; <span class="hljs-built_in">Unit</span>, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onRegister: () -&gt; <span class="hljs-built_in">Unit</span>, 
) : BaseComponent(componentContext, coroutineContext), LoginComponent { 
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> model = 
        LoginModel( 
            login = InputText( 
                type = InputText.Type.NORMAL, 
                label = <span class="hljs-string">"Login"</span>, 
            ), 
            pass = InputText( 
                type = InputText.Type.SECURE, 
                label = <span class="hljs-string">"Password"</span>, 
            ), 
            loginButton = Button( 
                style = Button.Style.FILLED, 
                text = <span class="hljs-string">"Login"</span>, 
                onClick = { onLoginClick() }, 
            ), 
            registerButton = Button( 
                style = Button.Style.OUTLINED, 
                text = <span class="hljs-string">"Register"</span>, 
                onClick = { onRegisterClick() }, 
            ), 
        ) 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onLoginClick</span><span class="hljs-params">()</span></span> { 
        <span class="hljs-keyword">val</span> login = model.login.text.value 
        <span class="hljs-keyword">val</span> pass = model.pass.text.value 

        scope.launch { 
            loginRepository.login(login, pass) 
            onLogin() 
        } 
    } 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onRegisterClick</span><span class="hljs-params">()</span></span> { 
        onRegister() 
    } 
}
</code></pre>
<p>Using the previously created <code>scope</code> in the <code>BaseComponent</code>, we can call the suspend function, which will perform <strong>the login</strong> operation with the <strong>httpClient</strong>. The <code>onLogin()</code> lambda will be invoked if the API call finishes successfully. The lambda is handled in the <code>RootComponent</code> and will perform the navigation. The <code>login()</code> method will call the API and store the received access token in the <code>TokenRepository</code>. Every subsequent API call will be made securely with the authorization token.</p>
<h1 id="heading-screen-view">Screen View</h1>
<p>Let’s add some final touches to the <code>LoginScreen</code>, and we will be ready to run it on all three platforms.</p>
<p><code>composeApp/commonMain/features/login/LoginScreen.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">( 
    component: <span class="hljs-type">LoginComponent</span>, 
    model: <span class="hljs-type">LoginModel</span>, 
    modifier: <span class="hljs-type">Modifier</span>, 
)</span></span> { 
    Column( 
        modifier = modifier.fillMaxSize(), 
        horizontalAlignment = Alignment.CenterHorizontally, 
        verticalArrangement = Arrangement.Center, 
    ) { 
        Card(modifier = Modifier.fillMaxWidth()) { 
            Column(modifier = Modifier.padding(<span class="hljs-number">8</span>.dp)) { 
                Text(text = <span class="hljs-string">"GAME SHOP!"</span>) 
                Spacer(Modifier.height(<span class="hljs-number">16</span>.dp)) 
                model.login.Widget(Modifier.fillMaxWidth()) 
                Spacer(Modifier.height(<span class="hljs-number">16</span>.dp)) 
                model.pass.Widget(Modifier.fillMaxWidth()) 
                Spacer(Modifier.height(<span class="hljs-number">16</span>.dp)) 
                model.loginButton.Widget(Modifier.fillMaxWidth()) 
            } 
        } 
    } 
}
</code></pre>
<p>The <code>Content()</code> function should be displayed on the screen. Elements are ordered in the <code>Column</code> and positioned at the center of the screen. The login form is wrapped in the <code>Card</code> component and built with the previously created widgets. When we run all our targets, we should see something like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721042162988/34873fc9-50c0-4c91-b06f-19a46157da6f.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-handling-ui-states">Handling UI states</h1>
<p>After pressing the login button and successfully making an API call, the app should transition to the games list screen. This process involves fetching all the game data from the backend before displaying the content to the user. To achieve this, we need to introduce a state that holds information about the view itself. This state should be generic and capable of handling any component model. We will use a marker interface for models, a sealed class to represent the current UI state and a component interface that will force such an approach on all components.</p>
<p><code>shared/commonMain/features/utils/Model.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Model</span></span>
</code></pre>
<p><code>shared/commonMain/features/utils/ModelState.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ModelState</span>&lt;<span class="hljs-type">T : Model</span>&gt; </span>{ 
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Loading</span>&lt;<span class="hljs-type">T : Model</span>&gt; : <span class="hljs-type">ModelState</span>&lt;<span class="hljs-type">T</span>&gt;</span>() 
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Success</span>&lt;<span class="hljs-type">T : Model</span>&gt;</span>(<span class="hljs-keyword">val</span> model: T) : ModelState&lt;T&gt;() 
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Error</span>&lt;<span class="hljs-type">T : Model</span>&gt;</span>(<span class="hljs-keyword">val</span> message: String) : ModelState&lt;T&gt;() 
}
</code></pre>
<p><code>shared/commonMain/features/Component.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Component</span>&lt;<span class="hljs-type">T : Model</span>&gt; </span>{ 
    <span class="hljs-keyword">val</span> modelValue: Value&lt;ModelState&lt;T&gt;&gt; 
}
</code></pre>
<p>From the <strong>UI</strong> point of view, we need to implement a collector that can handle state changes and display proper views. We can create a generic extension function for the <strong>Component</strong> interface. The function will subscribe to the model changes and change views according to the current state. We can define the default behaviors for loading and error states and pass them as lambda expressions. They can be easily changed if some screens handle them differently.</p>
<p><code>composeApp/commonMain/features/game/GamesScreen.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T : Model&gt;</span> Component<span class="hljs-type">&lt;T&gt;</span>.<span class="hljs-title">observeModel</span><span class="hljs-params">( 
    loading: @<span class="hljs-type">Composable</span> () -&gt; <span class="hljs-type">Unit</span> = { DefaultProgressIndicator()</span></span> }, 
    error: <span class="hljs-meta">@Composable</span> (String) -&gt; <span class="hljs-built_in">Unit</span> = { Text(<span class="hljs-string">"Error: <span class="hljs-variable">$it</span>"</span>) }, 
    content: <span class="hljs-meta">@Composable</span> (T) -&gt; <span class="hljs-built_in">Unit</span>, 
) { 
    <span class="hljs-keyword">when</span> (<span class="hljs-keyword">val</span> modelState = <span class="hljs-keyword">this</span>.modelValue.subscribeAsState().value) { 
        <span class="hljs-keyword">is</span> ModelState.Loading -&gt; loading() 
        <span class="hljs-keyword">is</span> ModelState.Success -&gt; content(modelState.model) 
        <span class="hljs-keyword">is</span> ModelState.Error -&gt; error(modelState.message) 
    } 
} 


<span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">DefaultProgressIndicator</span><span class="hljs-params">()</span></span> { 
    Column( 
        Modifier.fillMaxSize(), 
        verticalArrangement = Arrangement.Center, 
        horizontalAlignment = Alignment.CenterHorizontally, 
    ) { 
        CircularProgressIndicator(modifier = Modifier.size(<span class="hljs-number">100</span>.dp)) 
    } 
}
</code></pre>
<h1 id="heading-game-list-screen">Game list screen</h1>
<p>Following the same principles as with the <code>LoginComponent</code>, we can now create the <code>GameListComponent</code>, which will display all the games fetched from the API, but with newly introduced tools.</p>
<p><code>shared/commonMain/features/games/list/GameListModel.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GamesListModel</span></span>( 
    <span class="hljs-keyword">val</span> games: List&lt;Item&gt;, 
) : Model { 
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Item</span></span>( 
        <span class="hljs-keyword">val</span> id: String, 
        <span class="hljs-keyword">val</span> name: String, 
        <span class="hljs-keyword">val</span> description: String, 
        <span class="hljs-keyword">val</span> image: String, 
        <span class="hljs-keyword">val</span> price: String, 
    ) 
}
</code></pre>
<p><code>shared/commonMain/features/games/list/GameListComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">GamesListComponent</span> : <span class="hljs-type">Component</span>&lt;<span class="hljs-type">GamesListModel</span>&gt;</span>
</code></pre>
<p><code>shared/commonMain/features/games/list/RealGameListComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealGamesListComponent</span></span>( 
    componentContext: ComponentContext, 
    coroutineContext: CoroutineContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> gamesRepository: GamesRepository 
) : BaseComponent(componentContext, coroutineContext), GamesListComponent { 
   ... 
}
</code></pre>
<p>Using <code>GameListComponent</code> requires us to implement the <code>modelValue</code> field. This field should be visible to the <strong>UI</strong> part of the application, but it should only be modifiable by the component itself. To achieve this, we need to introduce another mutable state. Initially, the state of the UI should be set to <strong>loading</strong>. In the <code>init</code> block, we can then use a coroutine scope to fetch the games from the repository. As the games are being fetched, the state will remain <strong>loading</strong>.</p>
<p>Once the games are successfully fetched, we will transition to the <strong>Success</strong> state, updating the <code>modelValue</code> with the retrieved data. This means the UI will now display the list of games. However, if the call to fetch games fails for any reason, we should transition to an <strong>Error</strong> state. This state will inform the UI that something went wrong, allowing it to display an appropriate error message to the user.</p>
<p>By managing these states—<strong>loading</strong>, <strong>Success</strong>, and <strong>Error</strong>—we ensure that the UI remains responsive and informative, providing users with a clear understanding of what is happening behind the scenes. This approach also makes our component more robust and easier to maintain, as the state management logic is centralized within the component itself.</p>
<p><code>shared/commonMain/features/games/list/RealGameListComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> modelState: MutableValue&lt;ModelState&lt;GamesListModel&gt;&gt; = 
    MutableValue(ModelState.Loading()) 

<span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> modelValue: Value&lt;ModelState&lt;GamesListModel&gt;&gt; = modelState
</code></pre>
<p><code>shared/commonMain/features/games/list/RealGameListComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">init</span> { 
    scope.launch { 
        <span class="hljs-keyword">try</span> { 
            <span class="hljs-keyword">val</span> games = gamesRepository.getGames() 
            <span class="hljs-keyword">val</span> model = GamesModelMapper.mapModel(games) 
            modelState.update { ModelState.Success(model) } 
        } <span class="hljs-keyword">catch</span> (e: Exception) { 
            modelState.update { ModelState.Error(<span class="hljs-string">"Something went wrong"</span>) } 
        } 
    } 
}
</code></pre>
<p>The model mapper uses a domain <code>Game</code> object and transforms it into a UI model so that the application knows how to display it on the screen.</p>
<p><code>shared/commonMain/features/games/list/GamesModelMapper.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> GamesModelMapper { 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">mapModel</span><span class="hljs-params">(games: <span class="hljs-type">List</span>&lt;<span class="hljs-type">Game</span>&gt;)</span></span>: GamesListModel { 
        <span class="hljs-keyword">return</span> GamesListModel( 
            games = 
                games.map { game -&gt; 
                    GamesListModel.Item( 
                        id = game.id, 
                        name = game.name, 
                        description = game.description, 
                        image = game.imageUrl, 
                        price = game.price, 
                    ) 
                } 
        ) 
    } 
}
</code></pre>
<p>Going back to <code>RealRootComponent</code>, we need to handle the new configuration, navigate, and create the proper component with the component factory.</p>
<p><code>shared/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span> 
<span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Games : Config
</code></pre>
<p><code>shared/commonMain/features/RootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GamesChild</span></span>(<span class="hljs-keyword">val</span> component: GamesListComponent) : Child()
</code></pre>
<p><code>shared/commonMain/features/factory/ComponentFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createGamesListComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: GamesListComponent
</code></pre>
<p><code>shared/commonMain/features/factory/RealComponentFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createGamesListComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: GamesListComponent { 
    <span class="hljs-keyword">return</span> RealGamesListComponent( 
        componentContext, 
        mainContext, 
        remoteRepository.gamesRepository() 
    ) 
}
</code></pre>
<p><code>shared/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin">Config.Games -&gt; 
    RootComponent.Child.GamesChild( 
        componentFactory.createGamesListComponent(componentContext = componentContext) 
    )
</code></pre>
<p><code>composeApp/commonMain/features/RootScreen.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">is</span> RootComponen.Child.GamesChild -&gt; GamesScreen(child.component)
</code></pre>
<p><code>composeApp/commonMain/features/game/GamesScreen.kt</code></p>
<pre><code class="lang-kotlin">composeApp/commonMain/features/game/GamesScreen.kt

<span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">internal</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">GamesScreen</span><span class="hljs-params">(component: <span class="hljs-type">GamesListComponent</span>)</span></span> { 
    component.observeModel { model -&gt; 
            Content(component, model) 
    } 
} 

<span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Content</span><span class="hljs-params">( 
    component: <span class="hljs-type">GamesListComponent</span>, 
    model: <span class="hljs-type">GamesListModel</span>, 
)</span></span> { 
    Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())) { 
        model.games.forEach { game -&gt; 
            <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Use game.Widget() here</span>
            Spacer(modifier = Modifier.height(<span class="hljs-number">8</span>.dp)) 
        } 
    } 
}
</code></pre>
<h2 id="heading-image-processing">Image processing</h2>
<p>With the created component, we must now focus on the UI layer. This involves designing the widget for the game list item. The widget will include standard elements such as Column, Row, Spacer, Card, and Text. Additionally, the API will provide us with the image <strong>URL</strong>, which we need to display as the thumbnail for each game.</p>
<p>To handle image processing in our multiplatform application, we can use <a target="_blank" href="https://coil-kt.github.io/coil/">COIL</a>, an efficient image-loading library. Despite the initial impression that image processing might be complex in a multiplatform environment, COIL makes it straightforward. Since version <code>3.0.0</code>, COIL has offered comprehensive support for multiplatform development. It leverages the KTOR engine to fetch images from the Web, ensuring smooth and efficient image loading.</p>
<p>Using COIL, we can easily load and display images in our application. The library provides a simple API to load images from URLs, handle caching, and display them in our UI components. This means we can focus on other aspects of our application without worrying about the intricacies of image loading and processing.</p>
<h3 id="heading-dependencies-1">Dependencies</h3>
<p><code>gradle/libs.versions.toml</code></p>
<pre><code class="lang-kotlin">coil = <span class="hljs-string">"3.0.0-SNAPSHOT"</span> 
... 
coil-coil = { group = <span class="hljs-string">"io.coil-kt.coil3"</span>, name = <span class="hljs-string">"coil"</span>, version.ref = <span class="hljs-string">"coil"</span> } 
coil-compose = { group = <span class="hljs-string">"io.coil-kt.coil3"</span>, name = <span class="hljs-string">"coil-compose"</span>, version.ref = <span class="hljs-string">"coil"</span> } 
coil-network-ktor = { group = <span class="hljs-string">"io.coil-kt.coil3"</span>, name = <span class="hljs-string">"coil-network-ktor"</span>, version.ref = <span class="hljs-string">"coil"</span> }
</code></pre>
<p><code>composeApp/build.gradle.kts</code></p>
<pre><code class="lang-kotlin">implementation(libs.coil.coil) 
implementation(libs.coil.compose) 
implementation(libs.coil.network.ktor)
</code></pre>
<h3 id="heading-usage">Usage</h3>
<p><code>composeApp/commonMain/ui/widget/game/Game.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-function"><span class="hljs-keyword">fun</span> GamesListModel.Item.<span class="hljs-title">Widget</span><span class="hljs-params">(onClick: () -&gt; <span class="hljs-type">Unit</span>)</span></span> { 
    Card( 
        modifier = Modifier.fillMaxWidth(), 
        onClick = onClick, 
    ) { 
        Row( 
            modifier = Modifier.padding(<span class="hljs-number">8</span>.dp), 
            verticalAlignment = Alignment.CenterVertically, 
        ) { 
            AsyncImage( 
                modifier = Modifier.height(<span class="hljs-number">100</span>.dp).width(<span class="hljs-number">80</span>.dp), 
                model = 
                ImageRequest.Builder(LocalPlatformContext.current) 
                    .<span class="hljs-keyword">data</span>(image) 
                    .build(), 
                contentDescription = <span class="hljs-literal">null</span>, 
                contentScale = ContentScale.Fit 
            ) 
            Spacer(modifier = Modifier.requiredWidth(<span class="hljs-number">8</span>.dp)) 
            Column( 
                modifier = Modifier.weight(<span class="hljs-number">1f</span>), 
            ) { 
                Text(text = name, fontWeight = FontWeight.Bold) 
                Text( 
                    text = description, 
                    fontWeight = FontWeight.Light, 
                    maxLines = <span class="hljs-number">4</span>, 
                    overflow = TextOverflow.Ellipsis 
                ) 
            } 
            Spacer(modifier = Modifier.requiredWidth(<span class="hljs-number">8</span>.dp)) 
            Column(horizontalAlignment = Alignment.CenterHorizontally) { 
                Text(text = <span class="hljs-string">"Price"</span>, fontWeight = FontWeight.Bold) 
                Text(text = price) 
            } 
        } 
    } 
}
</code></pre>
<h1 id="heading-adjusting-backend">Adjusting Backend</h1>
<p>The last thing to do is to populate our backend application with some data. We can insert data from <strong>Wikipedia</strong> into the database at the start of the application.</p>
<p><code>server/database/DatabaseInitializer.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">addDefaultGames</span><span class="hljs-params">()</span></span> { 
    GamesEntity.new { 
        name = <span class="hljs-string">"Doom"</span> 
        description = <span class="hljs-string">"Doom is a first-person shooter game developed and published by id Software."</span> 
        imageUrl = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/en/5/57/Doom_cover_art.jpg"</span> 
        price = <span class="hljs-string">"10.00"</span> 
    } 

    GamesEntity.new { 
        name = <span class="hljs-string">"Quake"</span> 
        description = <span class="hljs-string">"Quake is a first-person shooter game developed by id Software and published by GT Interactive."</span> 
        imageUrl = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/en/4/4c/Quake1cover.jpg"</span> 
        price = <span class="hljs-string">"5.00"</span> 
    } 

    GamesEntity.new { 
        name = <span class="hljs-string">"Duke Nukem 3D"</span> 
        description = <span class="hljs-string">"Duke Nukem 3D is a first-person shooter video game developed by 3D Realms."</span> 
        imageUrl = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/en/6/61/Duke_Nukem_3D_Coverart.png"</span> 
        price = <span class="hljs-string">"15.00"</span> 
    } 

    GamesEntity.new { 
        name = <span class="hljs-string">"Wolfenstein 3D"</span> 
        description = <span class="hljs-string">"Wolfenstein 3D is a first-person shooter video game developed by id Software and published by Apogee Software and FormGen."</span> 
        imageUrl = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/en/0/05/Wolfenstein-3d.jpg"</span> 
        price = <span class="hljs-string">"12.00"</span> 
    } 
}
</code></pre>
<p><code>server/database/RealDatabaseFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">object</span> SchemaDefinition { 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createSchema</span><span class="hljs-params">()</span></span> { 
        transaction { 
           ... 
           addDefaultGames() 
        } 
    } 
}
</code></pre>
<p>Now, we can run the server and the applications and check what the game list screen looks like.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721043937293/a4f469e7-7a33-46fc-ba70-43df45394d3b.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-summary">Summary</h1>
<p>That’s all! With these components in place, you can build so many more screens and features for the Game Shop! Imagine the possibilities with Kotlin and Compose’s Multiplatform approach—you can create Android, iOS, and Web applications all from one codebase! And guess what? If you want to support desktops too, just add the Desktop target in <strong>the ComposeApp</strong> module, and it will work almost immediately. How awesome is that?!</p>
<p>I hope these blog posts introduced you to the beautiful world of multiplatform applications and showed that this is easier than it looks at first glance. I strongly encourage you to fetch the repo and play around with it, adding some new features, changing the UI, and handling API errors gently—there are many things to do. If you have any questions, don’t hesitate to ask.!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721044362237/d9932e64-345d-43ab-8859-cb443fc5c0fe.gif" alt class="image--center mx-auto" /></p>
<h2 id="heading-whats-more">What's more?</h2>
<p>The GitHub repository implements more features if you want to stay and play around or explore the code.</p>
<ul>
<li><p><code>HomeComponent</code> with bottom menu that holds game list and user orders</p>
</li>
<li><p><code>GameDetailsComponent</code>, which will display the extended description of a game</p>
</li>
<li><p><code>AddGameComponent</code>, which allows the addition of new games</p>
</li>
<li><p>Basic <strong>ADMIN</strong> role handling that helps to view a list of users in <code>UsersListComponent</code></p>
</li>
<li><p>Simple input <strong>validation</strong> on <code>LoginComponent</code></p>
</li>
<li><p>Simple animation of custom loading indicator</p>
</li>
<li><p>Paddings modifier for <strong>WEB</strong> wider screens</p>
</li>
</ul>
<blockquote>
<p>In this article, I transition to building the UI layer for a cross-platform application using Compose Multiplatform. We leverage a single codebase to create UI components like text fields, buttons, and models that seamlessly work across Android, iOS, and Web. The implementation involves state management, integrating COIL for image loading, and constructing multiple screen components, such as a login screen and a game list screen. The entire project, along with additional features like admin role handling and input validation, is available on GitHub. Readers are encouraged to explore and extend the application's functionality.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Complete Guide to Becoming a Fullstack Kotlin Developer - application architecture with Decompose]]></title><description><![CDATA[A step-by-step guide to building a fullstack Kotlin app using Decompose for web and mobile architecture]]></description><link>https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-application-architecture-with-decompose</link><guid isPermaLink="true">https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-application-architecture-with-decompose</guid><category><![CDATA[Decompose]]></category><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[navigation]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[architecture]]></category><category><![CDATA[Architecture Design]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[full stack]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Fri, 17 May 2024 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721034012275/e82bab24-5f04-49f0-b092-957125c4462d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <a target="_blank" href="https://hashnode.com/post/clyl39acc000009kxheb83i01">post</a>, I discussed common HTTP clients for Android, iOS, and web applications. We are gradually reaching the stage where we can present the data to the users. To achieve this, we need to properly structure our code, especially since we have already completed the repository layer. Now, it’s time to focus on building the presentation layer.</p>
<p>For this purpose, we will use <a target="_blank" href="https://arkivanov.github.io/Decompose/">Decompose</a>, a Kotlin multiplatform library. Decompose allows us to create lifecycle-aware business logic components and manage routing effectively. One of the reasons I chose Decompose is its robust support for <strong>wasm</strong> (WebAssembly), which makes it highly versatile for different platforms.</p>
<p>Decompose provides a clean way to organize our code, ensuring that our business logic is separated from the UI components. This separation is crucial for maintaining a clean architecture and making our codebase more manageable and scalable. Additionally, Decompose's routing capabilities will help us navigate between different screens or components within our application seamlessly.</p>
<p>By leveraging Decompose, we can ensure that our application is not only well-structured but also capable of handling complex business logic across multiple platforms. This will ultimately lead to a better user experience and a more maintainable codebase.</p>
<blockquote>
<p><em>The complete project is avaiable on</em> <a target="_blank" href="https://github.com/mkonkel/GameShop"><em>GitHub</em></a></p>
</blockquote>
<hr />
<h2 id="heading-dependencies">Dependencies</h2>
<p><code>libs.versions.toml</code></p>
<pre><code class="lang-kotlin">[versions] 
decompose = <span class="hljs-string">"3.0.0-alpha04"</span> 
essenty = <span class="hljs-string">"2.0.0-alpha02"</span> 

[libraries] 
decompose-core = { module = <span class="hljs-string">"com.arkivanov.decompose:decompose"</span>, version.ref = <span class="hljs-string">"decompose"</span> } 
decompose-extensions-compose = { module = <span class="hljs-string">"com.arkivanov.decompose:extensions-compose"</span>, version.ref = <span class="hljs-string">"decompose"</span> } 
essenty-lifecycle = { group = <span class="hljs-string">"com.arkivanov.essenty"</span>, name = <span class="hljs-string">"lifecycle"</span>, version.ref = <span class="hljs-string">"essenty"</span> } 
essenty-stateKeeper = { group = <span class="hljs-string">"com.arkivanov.essenty"</span>, name = <span class="hljs-string">"state-keeper"</span>, version.ref = <span class="hljs-string">"essenty"</span> } 
essenty-instanceKeeper = { group = <span class="hljs-string">"com.arkivanov.essenty"</span>, name = <span class="hljs-string">"instance-keeper"</span>, version.ref =<span class="hljs-string">"essenty"</span> } 
essenty-backHandler = { group = <span class="hljs-string">"com.arkivanov.essenty"</span>, name = <span class="hljs-string">"back-handler"</span>, version.ref = <span class="hljs-string">"essenty"</span> }
</code></pre>
<p><code>shared/build.gradle.kts</code></p>
<pre><code class="lang-kotlin">commonMain.dependencies { 
    ... 
    implementation(libs.decompose.core) 
    implementation(libs.essenty.lifecycle) 
    api(libs.essenty.stateKeeper) 
    api(libs.essenty.backHandler) 
}
</code></pre>
<h2 id="heading-components">Components</h2>
<p>With Decompose, we can create classes called <code>Components</code> that act as our presenters. These components need to implement the <code>ComponentContext</code> interface. This is where all interactions occur: API calls, building UI models, updating views, handling user interactions, and more. If you're an Android developer, you can think of them as <code>ViewModels</code>.</p>
<p>Decompose builds a stack of components and provides an easy way to navigate through them. <code>Components</code> that aren’t currently visible are not destroyed; they can keep working in the background without an attached UI. For more details about Decompose, I encourage you to read the documentation.</p>
<p>With this brief overview, we can create the <code>RootComponent</code>, the entry point of our application. This component will host all other components (sub-components/screens) and will live as long as the entire application.</p>
<p><code>shared/features/RootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">RootComponent</span> </span>{ 
    <span class="hljs-keyword">val</span> childStack: Value&lt;ChildStack&lt;*, Child&gt;&gt; 

    <span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> </span>{ 
        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginChild</span></span>(<span class="hljs-keyword">val</span> component: LoginComponent) : Child() 
        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RegisterChild</span></span>(<span class="hljs-keyword">val</span> component: RegisterComponent) : Child() 
    } 
}
</code></pre>
<p>Every Component that can host other components needs to provide a <code>childStack</code> – a holder value for current components. The <code>childStack</code> is visible to the platform, and based on its values, the <strong>UI</strong> will be determined. It can return the actual (top child) and backStack (inactive children) or all of the items. The <code>Child</code> sealed class represents components that can be hosted by the <code>RootComponent</code>. It also acts as a wrapper for the other <code>Components</code>.</p>
<p><code>shared/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealRootComponent</span></span>( 
    componentContext: ComponentContext, 
) : RootComponent, ComponentContext <span class="hljs-keyword">by</span> componentContext {}
</code></pre>
<p>The <code>context</code> provides us with the whole <code>lifecycle-aware</code> features and helps us implement behaviors like stack navigation. The navigation requires a <code>Configuration</code> of the set of parameters, values, or any other things that are necessary to create sub-components. The configuration should be created by us and needs to be <code>serializable</code> – the most common pattern is to use a sealed class again.</p>
<p><code>shared/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> navigation = StackNavigation&lt;Config&gt;() 

<span class="hljs-meta">@Serializable</span> 
<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Config</span> </span>{ 
    <span class="hljs-meta">@Serializable</span> 
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Login : Config 
    <span class="hljs-meta">@Serializable</span> 
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Register : Config 
}
</code></pre>
<p>Following the same rules, we can create <code>LoginComponent</code> and <code>RegisterComponent</code> that will hold the login form. All the screens that can be reached from the <code>RootComponent</code> must be defined in child and config classes. Of course, different configurations may lead us to the same components.</p>
<p><code>shared/commonMain/features/login/LoginComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">LoginComponent</span> </span>{ 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onRegisterClick</span><span class="hljs-params">()</span></span> 
}
</code></pre>
<p><code>shared/commonMain/features/login/RealLoginComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealLoginComponent</span></span>( 
    componentContext: ComponentContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onRegister: () -&gt; Unitt 
) : LoginComponent, ComponentContext <span class="hljs-keyword">by</span> componentContext { 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onRegisterClick</span><span class="hljs-params">()</span></span> { 
        onRegister() 
    } 
}
</code></pre>
<p>Now we can write a function that will use the configuration to create a child component. Let's call this function <code>childFactory</code>. This function will take the configuration as an input parameter and return the appropriate child component based on the configuration type.</p>
<p><code>shared/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">childFactory</span><span class="hljs-params">( 
    config: <span class="hljs-type">Config</span>, 
    componentContext: <span class="hljs-type">ComponentContext</span>, 
)</span></span> = <span class="hljs-keyword">when</span> (config) { 
    Config.Login -&gt;  
       RootComponent.Child.LoginChild( 
             RealLoginComponent(componentContext = componentContext) 
       ) 
}
</code></pre>
<h2 id="heading-navigation">Navigation</h2>
<p>The last thing is to create a <code>childStack</code> that will manage the navigation. It will also be responsible for creating children and managing the components. It should have a <strong>unique key</strong>, <strong>navigation source</strong>, <strong>serializer</strong> that determines how to serialize the configuration, a flag that determines if the stack should handle the <strong>back button</strong>, an <strong>initial stack</strong> from which the component should start, and a <strong>child factory</strong> for creating new subcomponents.</p>
<pre><code class="lang-kotlin"> <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> stack = childStack( 
    key = <span class="hljs-string">"RootComponent"</span>, 
    source = navigation, 
    serializer = Config.serializer(), 
    handleBackButton = <span class="hljs-literal">true</span>, 
    initialStack = { listOf(Config.Login) }, 
    childFactory = ::childFactory, 
) 

<span class="hljs-keyword">override</span> <span class="hljs-keyword">val</span> childStack: Value&lt;ChildStack&lt;*, RootComponent.Child&gt;&gt; = stack
</code></pre>
<p>The return type of the stack is <code>Value</code>, an internal <strong>Decompose</strong> way to provide an observable state (similar to the state in Jetpack Compose). It’s a custom class that gives us the flexibility to use the library on any platform we want.</p>
<p>With the above configuration, we can now handle the navigation events more effectively. By using the <code>onRegister</code> lambda in the <code>LoginComponent</code>, we can trigger a screen change in the <code>RootComponent</code>. This is achieved through the <code>pushNew</code> function, which pushes a new configuration onto the top of the current stack.</p>
<p>This approach offers several advantages. Firstly, it ensures that the entire navigation logic is decoupled from the underlying platforms. This means that the navigation logic is not tied to any specific platform, making it more versatile and easier to maintain. Secondly, this separation simplifies the navigation logic, allowing it to be unit-tested within the shared codebase. This eliminates the need to run additional devices or emulators for testing purposes, thereby speeding up the development and testing process.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">childFactory</span><span class="hljs-params">( 
    config: <span class="hljs-type">Config</span>, 
    componentContext: <span class="hljs-type">ComponentContext</span>, 
)</span></span> = <span class="hljs-keyword">when</span> (config) { 
    Config.Login -&gt; { 
        RootComponent.Child.LoginChild( 
            RealLoginComponent( 
                componentContext = componentContext, 
                onRegister = { 
                    navigation.pushNew(Config.Register) 
                }, 
            ), 
        ) 
    } 

    Config.Register -&gt; { 
        RootComponent.Child.RegisterChild( 
            RealRegisterComponent( 
                componentContext = componentContext, 
            ), 
        ) 
    } 
}
</code></pre>
<p>The last step is to create the <code>RootComponent</code> in the shared platform <strong>UI</strong> and start using the created stack. We begin at the entry point for all platforms with the <code>App()</code> function, which will initially only provide the <code>RootScreen</code>. </p>
<p><code>composeApp/commonMain/App.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">App</span><span class="hljs-params">( 
    component: <span class="hljs-type">RootComponent</span>, 
    modifier: <span class="hljs-type">Modifier</span>, 
)</span></span> { 
    RootScreen(component = component, modifier = modifier) 
}
</code></pre>
<p><code>composeApp/commonMain/features/RootScreen.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">RootScreen</span><span class="hljs-params">( 
    component: <span class="hljs-type">RootComponent</span>, 
    modifier: <span class="hljs-type">Modifier</span> = Modifier, 
)</span></span> { 
    Children( 
        stack = component.childStack, 
        modifier = modifier, 
        animation = stackAnimation(fade()), 
    ) { 
        <span class="hljs-keyword">when</span> (<span class="hljs-keyword">val</span> child = it.instance) { 
            <span class="hljs-keyword">is</span> RootComponent.Child.LoginChild -&gt; 
                LoginScreen(child.component) 

            <span class="hljs-keyword">is</span> RootComponent.Child.RegisterChild -&gt; 
                RegisterScreen(child.component) 
        } 
    } 
}
</code></pre>
<p>The <code>Children()</code> function is part of the <strong>Decompose</strong> library responsible for handling the <code>childStack</code> values. The last parameter of this function is a <strong>@Composable</strong> lambda that returns the current child and allows us to handle UI changes depending on the current child.</p>
<p><code>composeApp/commonMain/features/login/LoginScreen.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">internal</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">LoginScreen</span><span class="hljs-params">( 
    component: <span class="hljs-type">LoginComponent</span>, 
    modifier: <span class="hljs-type">Modifier</span> = Modifier, 
)</span></span> { 
    Button( 
        onClick = { 
            component.onRegisterClick() 
        }, 
        content = { 
            Text(<span class="hljs-string">"Register"</span>) 
        }, 
    ) 
}
</code></pre>
<p><code>composeApp/commonMain/features/register/RegisterScreen.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Composable</span> 
<span class="hljs-keyword">internal</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">RegisterScreen</span><span class="hljs-params">( 
    component: <span class="hljs-type">RegisterComponent</span>, 
    modifier: <span class="hljs-type">Modifier</span> = Modifier, 
)</span></span> { 
    Text(<span class="hljs-string">"This is the Register screen"</span>) 
}
</code></pre>
<p>Finally, it is time to use our <code>App()</code> function on every platform. On Android, we need to use the <code>retainedComponent</code> function that will handle orientation changes.</p>
<h3 id="heading-android">Android</h3>
<p><code>composeApp/androidMain/gameshop/MainActivity.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">ComponentActivity</span></span>() { 
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> { 
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState) 

        <span class="hljs-keyword">val</span> root = retainedComponent { RealRootComponent(componentContext = it) } 
        setContent { App(component = root, modifier = Modifier.fillMaxSize()) } 
    } 
}
</code></pre>
<h3 id="heading-ios">iOS</h3>
<p><code>composeApp/iosMain/gameshop/main.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">MainViewController</span><span class="hljs-params">()</span></span> = ComposeUIViewController { 
    <span class="hljs-keyword">val</span> root = remember { RealRootComponent(componentContext = DefaultComponentContext(LifecycleRegistry()),) } 

    App(component = root, modifier = Modifier.fillMaxSize()) 
}
</code></pre>
<h3 id="heading-web">Web</h3>
<p><code>composeApp/wasmJsMain/gameshop/main.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { 
    <span class="hljs-keyword">val</span> root = RealRootComponent(componentContext = DefaultComponentContext(lifecycle = LifecycleRegistry()),) 

    CanvasBasedWindow(title = <span class="hljs-string">"GameShop"</span>, canvasElementId = <span class="hljs-string">"gameShopCanvas"</span>) { 
        App(component = root, modifier = Modifier.fillMaxSize()) 
    } 
}
</code></pre>
<p>This was the basic setup of the <strong>Decompose,</strong> which we can follow for other screens. Nevertheless, having direct access to components implementation and creating them on your own is not a great approach. Since we have created a simple <strong>DI</strong> and we are using it for the repository layer we should extend it with the methods for creating components. </p>
<h2 id="heading-dependency-injection">Dependency Injection</h2>
<p><code>composeApp/commonMain/features/factory/ComponentFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ComponentFactory</span> </span>{ 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRootComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
    )</span></span>: RootComponent 

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRegisterComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span> 
    )</span></span>: RegisterComponent 

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createLoginComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
        onRegister: () -&gt; <span class="hljs-type">Unit</span>, 
    )</span></span>: LoginComponent 
}
</code></pre>
<p>Now, with the usage of the factory, we can inject it via the constructor into the <code>RootComponent</code>. This allows us to delegate the creation of sub-components to the factory, ensuring a more modular and maintainable codebase.</p>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealRootComponent</span></span>( 
    componentContext: ComponentContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> componentFactory: ComponentFactory, 
) : RootComponent, ComponentContext <span class="hljs-keyword">by</span> componentContext { 
    ... 
    Config.Register -&gt; { 
        RootComponent.Child.RegisterChild( 
            componentFactory.createRegisterComponent( 
                componentContext = componentContext, 
            ), 
        ) 
    } 
    ... 
}
</code></pre>
<p>The implementation of <code>ComponentFactory</code> will have all the necessary dependencies to create any component. With this approach, we don’t have to worry about creating any additional classes. We can also extend the <code>LoginComponent</code> and the <code>RegisterComponent</code> with additional properties such as repositories and lambda functions for user interactions. Lambdas will be passed from parent to child, but the repository is injected into the factory.</p>
<p><code>composeApp/commonMain/features/factory/RealComponentFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealComponentFactory</span></span>( 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> remoteRepository: RemoteRepository, 
) : ComponentFactory { 
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRootComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
    )</span></span>: RootComponent { 
        <span class="hljs-keyword">return</span> RealRootComponent( 
            componentContext = componentContext, 
            componentFactory = <span class="hljs-keyword">this</span>, 
        ) 
    } 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRegisterComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: RegisterComponent { 
        <span class="hljs-keyword">return</span> RealRegisterComponent( 
            componentContext = componentContext, 
            loginRepository = remoteRepository.loginRepository(), 
        ) 
    } 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createLoginComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
        onLogin: () -&gt; <span class="hljs-type">Unit</span>, 
        onRegister: () -&gt; <span class="hljs-type">Unit</span>, 
    )</span></span>: LoginComponent { 
        <span class="hljs-keyword">return</span> RealLoginComponent( 
            loginRepository = remoteRepository.loginRepository(), 
            onLogin = onLogin, 
            onRegister = onRegister, 
        ) 
    } 
}
</code></pre>
<p>The last thing to do is to add the factory and its implementation to the <strong>DI</strong> class and use it on the platforms.</p>
<p><code>composeApp/commonMain/di/DI.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> DI { 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokenStorage: TokenStorage = RealTokenStorage() 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> httpClientFactory: HttpClientFactory = HttpClientFactory(tokenStorage) 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> remoteRepository: RemoteRepository = RealRemoteRepository(httpClientFactory.create(), tokenStorage) 

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">rootComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
    )</span></span>: RootComponent { 
        <span class="hljs-keyword">return</span> RealComponentFactory(remoteRepository = remoteRepository) 
            .createRootComponent(componentContext = componentContext) 
    } 
}
</code></pre>
<p><code>composeApp/androidMain/gameshop/MainActivity.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> : <span class="hljs-type">ComponentActivity</span></span>() { 
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> { 
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState) 

        <span class="hljs-keyword">val</span> root = retainedComponent { DI.rootComponent(componentContext = it) } 
        setContent { App(component = root, modifier = Modifier.fillMaxSize()) } 
    } 
}
</code></pre>
<h2 id="heading-wiring-things-up">Wiring things up</h2>
<p>With the work we’ve done so far, where we introduced the presentation layer with various components, it's now time to integrate the <strong>API</strong> calls. Here's a detailed explanation of the process:</p>
<p>Assume the user clicks on the <strong>login</strong> button on the login screen. At this moment, the app will send an <strong>API</strong> request containing the user's credentials. This request is handled by our <code>remoteRepository</code>, which was set up earlier with the necessary <strong>HTTP client</strong> and <strong>token storage</strong>.</p>
<p>Upon receiving a successful response from the server, indicating that the login was successful, the <code>onLogin</code> lambda will be triggered. This lambda function is responsible for performing the next steps in the app's flow. Specifically, it will navigate the user to the <strong>home screen</strong>.</p>
<p>On the home screen, the user will be greeted with multiple sections. Two primary sections include the <strong>games list</strong>, which displays a curated list of games available to the user, and the <strong>orders</strong> section, where users can view their past and current orders.</p>
<p>The <code>HomeComponent</code> will be similar to the <code>RootComponent</code> as it will have its own stack with <code>GamesListComponent</code> and <code>OrdersComponent</code>. The screen will have bottom navigation that will allow you to switch views.</p>
<p>The API calls are made with <strong>suspend functions</strong>; for this reason, we need to invoke them from a <strong>coroutine scope</strong>. Therefore, every component should be able to create and provide its lifecycle-aware scope that can be used for making such requests. We can introduce a <code>BaseComponent</code> abstract class that will be responsible for handling the coroutine scope creation. Every component implementation should use it to avoid code duplication.</p>
<p><code>composeApp/commonMain/features/BaseComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BaseComponent</span></span>( 
    componentContext: ComponentContext, 
    coroutineContext: CoroutineContext, 
) : ComponentContext <span class="hljs-keyword">by</span> componentContext { 

    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">val</span> scope <span class="hljs-keyword">by</span> lazy { coroutineScope(coroutineContext + Dispatchers.Default + SupervisorJob()) } 

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">CoroutineScope</span><span class="hljs-params">( 
        context: <span class="hljs-type">CoroutineContext</span>, 
        lifecycle: <span class="hljs-type">Lifecycle</span>, 
    )</span></span>: CoroutineScope { 
        <span class="hljs-keyword">val</span> scope = CoroutineScope(context) 
        lifecycle.doOnDestroy { scope.coroutineContext.cancelChildren() } 
        <span class="hljs-keyword">return</span> scope 
    } 

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> LifecycleOwner.<span class="hljs-title">coroutineScope</span><span class="hljs-params">(context: <span class="hljs-type">CoroutineContext</span>)</span></span>: CoroutineScope = 
        CoroutineScope(context, lifecycle) 
}
</code></pre>
<p><code>shared/features/login/RealLoginComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealLoginComponent</span></span>( 
    componentContext: ComponentContext, 
    coroutineContext: CoroutineContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> loginRepository: LoginRepository, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onLogin: () -&gt; <span class="hljs-built_in">Unit</span>, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> onRegister: () -&gt; <span class="hljs-built_in">Unit</span>, 
) : BaseComponent(componentContext, coroutineContext), LoginComponent { 
    ... 
}
</code></pre>
<p>Let’s move forward and create a component factory, which will be used all over the app to help create components.</p>
<p><code>composeApp/commonMain/factory/ComponentFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ComponentFactory</span> </span>{ 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRootComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: RootComponent 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRegisterComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: RegisterComponent 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createLoginComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>, onLogin: () -&gt; <span class="hljs-type">Unit</span>, onRegister: () -&gt; <span class="hljs-type">Unit</span>, )</span></span>: LoginComponent 
}
</code></pre>
<p>Through the implementation, we can pass all the required dependencies to ensure that each component has everything it needs to function correctly. This approach allows us to inject specific dependencies, such as repositories, context, and callback functions, directly into the components. By doing so, we maintain a clean separation of concerns and promote reusability across different parts of the application.</p>
<p><code>composeApp/commonMain/factory/RealComponentFactory.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealComponentFactory</span></span>( 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> mainContext: CoroutineContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> remoteRepository: RemoteRepository, 
) : ComponentFactory { 
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRootComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>, )</span></span>: RootComponent { 
        <span class="hljs-keyword">return</span> RealRootComponent( 
            coroutineContext = mainContext, 
            componentContext = componentContext, 
            componentFactory = <span class="hljs-keyword">this</span>, 
        ) 
    } 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createRegisterComponent</span><span class="hljs-params">(componentContext: <span class="hljs-type">ComponentContext</span>)</span></span>: RegisterComponent { 
        <span class="hljs-keyword">return</span> RealRegisterComponent( 
            componentContext = componentContext, 
            coroutineContext = mainContext, 
            loginRepository = remoteRepository.loginRepository(), 
        ) 
    } 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createLoginComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
        onLogin: () -&gt; <span class="hljs-type">Unit</span>, 
        onRegister: () -&gt; <span class="hljs-type">Unit</span>, 
    )</span></span>: LoginComponent { 
        <span class="hljs-keyword">return</span> RealLoginComponent( 
            coroutineContext = mainContext, 
            componentContext = componentContext, 
            loginRepository = remoteRepository.loginRepository(), 
            onLogin = onLogin, 
            onRegister = onRegister, 
        ) 
    } 
}
</code></pre>
<p>Then in our <strong>ID</strong> object, we can replace the direct <code>RootComponent</code> call with the newly created factory. We also need to modify the platform call, and finally, the internals of the <code>RealRootComponent</code> to use the factory to create its sub-components. </p>
<p><code>composeApp/commonMain/di/DI.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> DI { 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokenStorage: TokenStorage = RealTokenStorage() 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> httpClientFactory: HttpClientFactory = HttpClientFactory(tokenStorage) 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> remoteRepository: RemoteRepository = RealRemoteRepository(httpClientFactory.create(), tokenStorage) 

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">rootComponent</span><span class="hljs-params">( 
        componentContext: <span class="hljs-type">ComponentContext</span>, 
        mainContext: <span class="hljs-type">CoroutineContext</span> 
    )</span></span>: RootComponent { 
        <span class="hljs-keyword">return</span> RealComponentFactory( 
            mainContext = mainContext, 
            remoteRepository = remoteRepository, 
        ).createRootComponent( 
            componentContext = componentContext, 
        ) 
    } 
}
</code></pre>
<p><code>composeApp/androidMain/gameshop/MainActivity.kt</code></p>
<pre><code class="lang-kotlin">DI.rootComponent(componentContext = it, mainContext = MainScope().coroutineContext)
</code></pre>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealRootComponent</span></span>( 
    componentContext: ComponentContext, 
    coroutineContext: CoroutineContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> componentFactory: ComponentFactory, 
) : BaseComponent(componentContext, coroutineContext), RootComponent { 
   ... 
   <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">childFactory</span><span class="hljs-params">( 
    config: <span class="hljs-type">Config</span>, 
    componentContext: <span class="hljs-type">ComponentContext</span>, 
)</span></span> = <span class="hljs-keyword">when</span> (config) { 
    Config.Login -&gt; { 
        RootComponent.Child.LoginChild( 
            componentFactory.createLoginComponent( 
                componentContext = componentContext, 
                onLogin = { 
                    navigation.pushNew(Config.Home) 
                }, 
                onRegister = { 
                    navigation.pushNew(Config.Register) 
                }, 
            ), 
        ) 
    } 

    Config.Register -&gt; { 
        RootComponent.Child.RegisterChild( 
            componentFactory.createRegisterComponent( 
                componentContext = componentContext, 
            ), 
        ) 
    } 
}
</code></pre>
<p>Since web application navigation is quite different from mobile – we can reach certain screens by passing a proper link – we need to ensure that this is handled. Thankfully, <strong>Decompose</strong> provides a tool to do it. The <code>WebHistoryController</code> is a connection between <code>childStack</code> and the <code>WebHistory</code> interface. It holds the web paths and can change the navigation according to the current address. We can also introduce a sealed class called <code>DeepLink</code> which will produce the current web path.</p>
<p><code>composeApp/commonMain/deepLink/DeepLink.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">DeepLink</span> </span>{ 
    <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> None : DeepLink 
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Web</span></span>(<span class="hljs-keyword">val</span> path: String) : DeepLink 
}
</code></pre>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@OptIn(ExperimentalDecomposeApi::class)</span> 
<span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealRootComponent</span></span>( 
    componentContext: ComponentContext, 
    coroutineContext: CoroutineContext, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> deepLink: DeepLink = DeepLink.None, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> webHistoryController: WebHistoryController? = <span class="hljs-literal">null</span>, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> componentFactory: ComponentFactory, 
) : BaseComponent(componentContext, coroutineContext), RootComponent { ... }
</code></pre>
<p>The <code>webHistoryController</code> needs to be attached to the stack and navigation. We need to pass the navigation, stack, and serializer. Then we need to find a way to change the web application path based on the current configuration. The <code>getPath</code> lambda provides the current configuration and requires a <code>String</code> in return. Similarly, the proper configuration should be returned for a given path and this is a role for the <code>getConfiguration</code> lambda, which takes a <code>String</code> and returns <code>Configuration</code>. </p>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">init</span> { 
    webHistoryController?.attach( 
        navigator = navigation, 
        stack = stack, 
        serializer = Config.serializer(), 
        getPath = ::getPathForConfig, 
        getConfiguration = ::getConfigForPath, 
    ) 
}
</code></pre>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getPathForConfig</span><span class="hljs-params">(config: <span class="hljs-type">Config</span>)</span></span>: String = 
    <span class="hljs-keyword">when</span> (config) { 
        Config.Login -&gt; <span class="hljs-string">"/login"</span> 
        Config.Register -&gt; <span class="hljs-string">"/register"</span> 
    }
</code></pre>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getConfigForPath</span><span class="hljs-params">(path: <span class="hljs-type">String</span>)</span></span>: Config = 
    <span class="hljs-keyword">when</span> (path.removePrefix(<span class="hljs-string">"/"</span>)) { 
        “login” -&gt; Config.Login 
        “register” -&gt; Config.Register 
        <span class="hljs-keyword">else</span> -&gt; Config.Login 
    }
</code></pre>
<p>The <code>childStack</code> function also needs to be modified. The <code>initialStack</code> might be constructed differently, based on the passed path. We will take the <code>webHistoryController</code> paths, iterate through them, and try to find a proper config for a given address. If we can’t find anything, we should initialize the default stack. For mobile apps (when there is no DeepLink), we are returning the <code>Login</code> configuration, but for the Web application with the provided address, we should try to resolve it.</p>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> stack = 
    childStack( 
        key = <span class="hljs-string">"RootComponent"</span>, 
        source = navigation, 
        serializer = Config.serializer(), 
        handleBackButton = <span class="hljs-literal">true</span>, 
        initialStack = { 
            getInitialStack( 
                webHistoryPaths = webHistoryController?.historyPaths, 
                deepLink = deepLink, 
            ) 
        }, 
        childFactory = ::childFactory, 
    )
</code></pre>
<p><code>composeApp/commonMain/features/RealRootComponent.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getInitialStack</span><span class="hljs-params">( 
    webHistoryPaths: <span class="hljs-type">List</span>&lt;<span class="hljs-type">String</span>&gt;?, 
    deepLink: <span class="hljs-type">DeepLink</span>, 
)</span></span>: List&lt;Config&gt; = 
    webHistoryPaths 
        ?.takeUnless(List&lt;*&gt;::isEmpty) 
        ?.map(::getConfigForPath) 
        ?: getInitialStack(deepLink) 

<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getInitialStack</span><span class="hljs-params">(deepLink: <span class="hljs-type">DeepLink</span>)</span></span>: List&lt;Config&gt; = 
    <span class="hljs-keyword">when</span> (deepLink) { 
        <span class="hljs-keyword">is</span> DeepLink.None -&gt; listOf(Config.Login) 
        <span class="hljs-keyword">is</span> DeepLink.Web -&gt; listOf(getConfigForPath(deepLink.path)) 
    }
</code></pre>
<p>Since we added two new parameters to the <code>RootComponent</code> constructor we need to update the <strong>factory</strong> and the <strong>platforms.</strong> We used default parameters in <code>RootComponent</code> so after adjusting the factory only the <strong>Web</strong> application entry point will be changed.</p>
<p><code>composeApp/iosMain/gameshop/main.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">MainViewController</span><span class="hljs-params">()</span></span> = ComposeUIViewController { 
<span class="hljs-keyword">val</span> root = 
    DI.rootComponent( 
        componentContext = DefaultComponentContext(lifecycle = LifecycleRegistry()), 
        deepLink = DeepLink.Web(path = window.location.pathname), 
        webHistoryController = DefaultWebHistoryController(), 
        mainContext = MainScope().coroutineContext, 
    ) 

    App(component = root, modifier = Modifier.fillMaxSize()) 
}
</code></pre>
<p>That’s all in the when it comes to app architecture. We’ve got the presentation layer ready, with some abstraction on top of it, a component factory, and a configured <strong>DI</strong>. Adding new functionalities should be straightforward, every new screen needs its component and should be added to the navigation.</p>
<p>We still missing one critical part – the <strong>UI</strong> layer. In the next blogpost, we will focus on providing <strong>UI</strong> models to the platforms and handling user interactions. We will create a simple login form and a home screen with a games list.  </p>
<blockquote>
<p>In this article, we delve into the presentation layer of a Kotlin multiplatform application using the Decompose library. We explore how to structure code with lifecycle-aware components, implement seamless navigation, and maintain a clean architecture. The guide covers setting up dependencies, creating components like <code>RootComponent</code>, managing navigation, and integrating with Kotlin's coroutine framework for async tasks. Additionally, we discuss the use of Dependency Injection for modularity and handling web-specific navigation. This foundational setup prepares our application for effective data presentation across Android, iOS, and web platforms.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Complete Guide to Becoming a Fullstack Kotlin Developer - Mobile and Web HTTP Client with KTOR]]></title><description><![CDATA[Comprehensive guide to becoming a Fullstack Kotlin Developer using KTOR for unified HTTP clients on Android, iOS, and web applications]]></description><link>https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-mobile-and-web-http-client-with-ktor</link><guid isPermaLink="true">https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-mobile-and-web-http-client-with-ktor</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[ktor client]]></category><category><![CDATA[ktor]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Full Stack Development]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Tue, 30 Apr 2024 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720931179478/587d7c5b-6bd1-4039-bc7c-60b3459b31e4.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post, you will gain a comprehensive understanding of how to create a unified HTTP client for Android, iOS, and web applications within a Compose Multiplatform project. We will be utilizing the powerful KTOR library as our client. This guide will walk you through the entire process, from setting up your project to implementing the HTTP client, and will include detailed code examples and explanations to ensure you can follow along easily. By the end of this post, you will have the knowledge and skills to efficiently manage network requests across different platforms using a single codebase.</p>
<blockquote>
<p>The complete project is avaiable on <a target="_blank" href="https://github.com/mkonkel/GameShop">GitHub</a></p>
</blockquote>
<hr />
<h2 id="heading-initial-setup">Initial setup</h2>
<p>In the previous <a target="_blank" href="https://hashnode.com/post/clyl1s3ec000709la6vp34zzx">post,</a> I covered common backend in which we decided that some objects can be shared across the app. Shared repository is a contract between a server and a client. We know exactly what methods are available and what data are served. Common objects also can save us a bit of time, there is no need to map them from one to another. It is time to use those objects in the frontend apps. First, we need to add the dependencies to the previously created modules in our shared module. </p>
<p><code>shared/build.gradle.kts</code></p>
<pre><code class="lang-kotlin">sourceSets { 
    commonMain.dependencies { 
        implementation(projects.domain) 
        implementation(projects.repository) 
      } 
}
</code></pre>
<p>Now we can start from we end of the last blog post by creating the implementation of the <code>GamesRepository</code> as the <code>HttpGamesRepository</code> in the common frontends code.</p>
<p><code>HttpGamesRepository.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HttpGamesRepository</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> client: HttpClient) : GamesRepository { 
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getGames</span><span class="hljs-params">()</span></span>: List&lt;Game&gt; { 
        <span class="hljs-keyword">return</span> client.<span class="hljs-keyword">get</span>(“/games”).body() 
    } 
}
</code></pre>
<p>If we take a good look at the previous backend code, it is almost the same as the <code>RealDatabaseRepository</code>. The only difference is that we need an <strong>HttpClient</strong> for the apps.</p>
<p>The most common multiplatform client is <a target="_blank" href="https://ktor.io/docs/create-client.html">KTOR</a>. It can be easily built into the KMM project without any additional code for each platform. It only needs a separate engine that can be provided via the dependencies. Following the documentation, we can create something like this.</p>
<blockquote>
<p>Please note that I am using the latest KTOR version with support for WASM, which is “3.0.0-wasm2”.</p>
</blockquote>
<p><code>libs.versions.toml</code></p>
<pre><code class="lang-kotlin">[versions] 
ktor-wasm = <span class="hljs-string">"3.0.0-wasm2"</span> 

[libraries] 
ktor-client-serialization-kotlinx-json = { module = <span class="hljs-string">"io.ktor:ktor-serialization-kotlinx-json"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-core = { module = <span class="hljs-string">"io.ktor:ktor-client-core"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-content-negotiation = { module = <span class="hljs-string">"io.ktor:ktor-client-content-negotiation"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-auth = { module = <span class="hljs-string">"io.ktor:ktor-client-auth"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-okhttp = { module = <span class="hljs-string">"io.ktor:ktor-client-okhttp"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-darwin = { module = <span class="hljs-string">"io.ktor:ktor-client-darwin"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-js = { module = <span class="hljs-string">"io.ktor:ktor-client-js"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> } 
ktor-client-logging = { module = <span class="hljs-string">"io.ktor:ktor-client-logging"</span>, version.ref = <span class="hljs-string">"ktor-wasm"</span> }
</code></pre>
<p><code>shared/build.gradle.kts</code></p>
<pre><code class="lang-kotlin">sourceSets { 
    commonMain.dependencies { 
    implementation(libs.ktor.client.core) 
    implementation(libs.ktor.client.logging) 
    implementation(libs.ktor.client.auth) 
    implementation(libs.ktor.client.content.negotiation) 
    implementation(libs.ktor.client.serialization.kotlinx.json) 

    implementation(libs.serialization) 
    } 

   iosMain.dependencies { 
       implementation(libs.ktor.client.darwin) 
   } 

   androidMain.dependencies { 
      implementation(libs.ktor.client.okhttp) 
   } 

   <span class="hljs-keyword">val</span> wasmJsMain <span class="hljs-keyword">by</span> getting { 
       dependencies { 
           implementation(libs.ktor.client.js) 
       } 
   } 
}
</code></pre>
<p>With the core dependencies added to the <strong>commonMain</strong> and the proper engines for the platforms, we can implement the client. The client can take the desired engine as a parameter to the <code>HttpClient</code> function, but if we leave it blank, the plugin will try to automatically provide a valid client based on the added dependencies – so for Android, it will be okHttp, and so on.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>: HttpClient { 
    <span class="hljs-keyword">return</span> HttpClient { 
        install(ContentNegotiation) { 
            json() 
        } 
        install(DefaultRequest) { 
            url(<span class="hljs-string">"http://localhost:3000"</span>) 
            contentType(ContentType.Application.Json) 
            accept(ContentType.Application.Json) 
        } 
        install(Auth) { 
            bearer { 
                loadTokens { 
                    TODO() 
                } 
                refreshTokens { 
        TODO() 
                } 
                sendWithoutRequest { request -&gt; 
                    <span class="hljs-keyword">when</span> (request.url.pathSegments.last()) { 
                        <span class="hljs-string">"login"</span> -&gt; <span class="hljs-literal">false</span> 
                        <span class="hljs-keyword">else</span> -&gt; <span class="hljs-literal">true</span> 
                    } 
                } 
            } 
        } 
    } 
}
</code></pre>
<p><strong>ContentNegotiation</strong> is a crucial component that handles the serialization and deserialization of requests and responses, ensuring that data is correctly formatted when being sent to and received from the server. This is especially important when dealing with JSON data, as it allows for seamless conversion between Kotlin objects and JSON strings.</p>
<p>With the <strong>DefaultRequest</strong> plugin, we can set up a default configuration for all outgoing requests. This includes specifying the base URL, which serves as the starting point for all relative URLs used in the client. Additionally, we can define common headers such as <code>Content-Type</code> and <code>Accept</code>, which inform the server about the type of data being sent and expected in return. This setup ensures that every request adheres to a consistent format, reducing the need for repetitive code.</p>
<p>The <strong>Auth</strong> plugin, combined with the <strong>bearer</strong> lambda, is responsible for managing authentication tokens. This plugin handles the acquisition and refreshing of tokens, which are essential for maintaining secure communication with the server. Within the <strong>bearer</strong> lambda, we define how to load the initial tokens and how to refresh them when they expire. This involves specifying functions that will be called to retrieve new tokens, ensuring that the client always has valid credentials.</p>
<p>Moreover, we can configure the <strong>Auth</strong> plugin to automatically add tokens to certain requests. The <code>sendWithoutRequest</code> function allows us to specify which endpoints should bypass token addition. For instance, in our setup, the <code>/login</code> endpoint is publicly accessible and does not require tokens. By returning <code>false</code> for this endpoint, we ensure that the client does not attempt to add tokens or handle 401 Unauthorized responses for login requests.</p>
<p>In scenarios where the server responds with an HTTP 401 Unauthorized status, the client is designed to automatically attempt to refresh the token. If successful, the client will retry the original request with the new token, thereby maintaining a seamless user experience without requiring manual intervention.</p>
<p>In our specific case, the <code>/login</code> endpoint is the only publicly available endpoint. This endpoint is responsible for providing a valid access token and user data upon successful authentication.</p>
<h2 id="heading-handling-authentication">Handling Authentication</h2>
<p>The lambda requires a <code>BearerTokens</code> object, which consists of two string values <code>accessToken</code> and <code>refreshToken</code>. If we want to be flexible, we need to store a token after every successful login and add it to every subsequent requests.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">TokenStorage</span> </span>{ 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">putTokens</span><span class="hljs-params">( 
        accessToken: <span class="hljs-type">String</span>, 
        refreshToken: <span class="hljs-type">String</span>, 
    )</span></span> 

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getToken</span><span class="hljs-params">()</span></span>: BearerTokens 
}
</code></pre>
<p>The implementation is as simple as it can be the values are stored in the <code>mutableList</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealTokenStorage</span> : <span class="hljs-type">TokenStorage { </span></span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokens = mutableSetOf&lt;BearerTokens&gt;() 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">putTokens</span><span class="hljs-params">( 
        accessToken: <span class="hljs-type">String</span>, 
        refreshToken: <span class="hljs-type">String</span>, 
    )</span></span> { 
        tokens.add(BearerTokens(accessToken, refreshToken)) 
    } 

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getToken</span><span class="hljs-params">()</span></span>: BearerTokens { 
        <span class="hljs-keyword">return</span> tokens.last() 
    } 
}
</code></pre>
<p>The updated <code>HttpClient</code> looks like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HttpClientFactory</span></span>( 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokenStorage: TokenStorage, 
) { 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>: HttpClient { 
        <span class="hljs-keyword">return</span> HttpClient { 
            ... 
            install(Auth) { 
                bearer { 
                    loadTokens { 
                        tokenStorage.getToken() 
                    } 
                    refreshTokens { 
                       TODO(“Not implemented uet”) 
                    } 
                    ... 
                } 
            } 
        } 
    } 
}
</code></pre>
<blockquote>
<p>Please notice that we don’t implement the refresh token mechanism as this is not important for the matter of the post. </p>
</blockquote>
<p>At the beginning, let's delve into the implementation details of the <code>HttpGamesRepository</code>. This repository is responsible for fetching game data from a remote server. However, before we can retrieve any game information, we need to authenticate the user and obtain a valid token. To handle this, I have introduced a <code>LoginRepository</code> along with its implementation.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">LoginRepository</span> </span>{ 
    <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">login</span><span class="hljs-params">(username: <span class="hljs-type">String</span>, password: <span class="hljs-type">String</span>)</span></span>: LoginResponse? 
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HttpLoginRepository</span></span>( 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> client: HttpClient, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokenStorage: TokenStorage, 
) : LoginRepository { 
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">login</span><span class="hljs-params">(username: <span class="hljs-type">String</span>, password: <span class="hljs-type">String</span> )</span></span>: LoginResponse? { 
        <span class="hljs-keyword">val</span> request = LoginRequest(username, password) 

        <span class="hljs-keyword">return</span> client.post(<span class="hljs-string">"/login"</span>) { setBody(request) }.body&lt;LoginResponse?&gt;() 
            .also { 
                <span class="hljs-keyword">if</span> (it != <span class="hljs-literal">null</span>) { 
                    tokenStorage.putTokens(it.token, <span class="hljs-string">"NOT IMPLEMENTED"</span>) 
                } 
            } 
    } 
}
</code></pre>
<p>Making requests with <strong>KTOR</strong> is simple. Using the provided <strong>login</strong> and <strong>password</strong>, we create a <code>LoginRequest</code>, and then we use the injected client (which has a base URL and headers configured by default).</p>
<p>We need to specify the <strong>method</strong> and <strong>path</strong> for our request. Then, in the lambda builder block, we add the <strong>body</strong> of the request and that's it - the request is ready.</p>
<p>To obtain the body of the response, we use a typed function that tries to receive the <strong>JSON</strong> and <strong>deserialize</strong> it to a given type.</p>
<p>To wrap things up and make everything work, it is very helpful to use a <strong>DI</strong> framework like KOIN. Unfortunately, at the time of writing this post, KOIN does not support the <strong>wasm</strong> target. In such cases, we need to create our own way of injection.</p>
<blockquote>
<p><em>When the blog post was published the KOIN added support for the</em> <strong><em>wasm*</em></strong>. Feel free to use it. I will do my best to update the project and add some explanations as soon as possible.* </p>
</blockquote>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> DI { 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokenStorage: TokenStorage = RealTokenStorage() 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> httpClientFactory: HttpClientFactory = HttpClientFactory(tokenStorage) 
    <span class="hljs-keyword">val</span> remoteRepository: RemoteRepository = RealRemoteRepository(httpClientFactory.create(), tokenStorage) 
}
</code></pre>
<p>I’ve added a factory for the remote repositories which will aggregate all the <code>HttpRepositories</code> in one class for simplicity. </p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">RemoteRepository</span> </span>{ 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">loginRepository</span><span class="hljs-params">()</span></span>: LoginRepository 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">gamesRepository</span><span class="hljs-params">()</span></span>: GamesRepository 
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealRemoteRepository</span></span>( 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> client: HttpClient, 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> tokenStorage: TokenStorage, 
) : RemoteRepository { 
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">loginRepository</span><span class="hljs-params">()</span></span>: LoginRepository = HttpLoginRepository(client, tokenStorage) 
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">gamesRepository</span><span class="hljs-params">()</span></span>: GamesRepository = HttpGamesRepository(client) 
}
</code></pre>
<p>With all the work done, we can use our <strong>DI</strong> and write a quick test to see if logging and fetching the games works. We can use the <code>jvmTest</code> module to hold tests for the standard code. To do so, we need some dependencies that will allow us to manage tests – <code>kotest</code>, <code>JUnit</code>, <code>coroutines</code>, and a valid client for the <strong>JVM</strong> target (we can use <code>KTOR</code> <code>CIO</code> or <code>OkHttp</code>). </p>
<p><code>libs.versions.toml</code></p>
<pre><code class="lang-kotlin">[versions] 
junit = <span class="hljs-string">"4.13.2"</span> 
kotest = <span class="hljs-string">"5.8.0"</span> 
coroutines = <span class="hljs-string">"1.8.0-RC2"</span> <span class="hljs-comment">// wasm support </span>

[libraries] 
junit = { group = <span class="hljs-string">"junit"</span>, name = <span class="hljs-string">"junit"</span>, version.ref = <span class="hljs-string">"junit"</span> } 
kotest-core = { module = <span class="hljs-string">"io.kotest:kotest-assertions-core"</span>, version.ref = <span class="hljs-string">"kotest"</span> } 
kotest-property = { module = <span class="hljs-string">"io.kotest:kotest-property"</span>, version.ref = <span class="hljs-string">"kotest"</span> } 
coroutines-test = { module = <span class="hljs-string">"org.jetbrains.kotlinx:kotlinx-coroutines-test"</span>, version.ref = <span class="hljs-string">"coroutines"</span> }
</code></pre>
<p><code>shared/build.gradle.kts</code></p>
<pre><code class="lang-kotlin">jvmTest.dependencies { 
    implementation(libs.ktor.client.okhttp) 
    implementation(libs.kotest.core) 
    implementation(libs.kotest.property) 
    implementation(libs.junit) 
    implementation(libs.coroutines.test) 
}
</code></pre>
<p>With the dependencies added we can write a simple repositories test. </p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HttpRepositoriesTest</span> </span>{ 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> loginRepository = DI.remoteRepository.loginRepository() 
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> gamesRepository = DI.remoteRepository.gamesRepository() 

    <span class="hljs-meta">@Test</span> 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> `login with valid credentials`<span class="hljs-params">()</span></span> = runTest { 
        <span class="hljs-keyword">val</span> result = loginRepository.login(<span class="hljs-string">"admin"</span>, <span class="hljs-string">"pass"</span>) 

        with(result.shouldNotBeNull()) { 
            token.shouldNotBeNull() 
            user.shouldNotBeNull() 
        } 
    } 

    <span class="hljs-meta">@Test</span> 
    <span class="hljs-function"><span class="hljs-keyword">fun</span> `should return all games`<span class="hljs-params">()</span></span> = runTest { 
        <span class="hljs-comment">// login first to get the token and store it in the token storage </span>
        loginRepository.login(<span class="hljs-string">"admin"</span>, <span class="hljs-string">"pass"</span>) 

        <span class="hljs-keyword">val</span> result = gamesRepository.getGames() 

        result.shouldNotBeEmpty() 
    } 
}
</code></pre>
<p>To sum things up, we have successfully set up a <strong>Kotlin multiplatform</strong> project that includes a fully functional <strong>KTOR</strong> backend and a common <strong>KTOR</strong> client capable of communicating with the running server. This setup allows us to send and fetch data seamlessly. The next step in our development process is to present this data to the application users in an intuitive and efficient manner.</p>
<p>Achieving this requires addressing several architectural tasks. First, we need to create a presentation layer that will display our data and manage user interactions. Additionally, we must implement a navigation system to guide users through different sections of the app, ensuring a smooth and coherent user experience.</p>
<p>In the upcoming blog post, we will delve deeper into the Mobile and Web Application Architecture using Decompose. We will explore how to structure the application, manage state, and handle navigation effectively. Stay tuned for a comprehensive guide that will help you build robust and scalable applications.</p>
<blockquote>
<p>This blog post provides a detailed guide on creating a unified HTTP client for Android, iOS, and web applications using Compose Multiplatform and the KTOR library. You'll learn how to set up your project, implement the HTTP client, and handle authentication tokens. The post includes step-by-step instructions, code examples, and explanations to help you manage network requests efficiently across multiple platforms using a single codebase.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Complete Guide to Becoming a Fullstack Kotlin Developer - scalable backend with KTOR]]></title><description><![CDATA[A comprehensive guide to becoming a Fullstack Kotlin Developer, focusing on scalable backend development with KTOR and role-based authorization]]></description><link>https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-scalable-backend-with-ktor</link><guid isPermaLink="true">https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-scalable-backend-with-ktor</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[ktor]]></category><category><![CDATA[backend]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[fullstack]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Fri, 26 Apr 2024 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720846566087/e16ab0d4-45e1-4c6f-80a2-5b89fc719e1a.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you don’t know what <strong>KTOR</strong> is, I strongly recommend checking my last post <a target="_blank" href="https://hashnode.com/post/clyichel900030al14zpe4e4i">KTOR as a backend</a>, where I guide you through the project setup and building your first REST API. In this blog post, I will use a lot of code from the mentioned project and just add it to the different modules.</p>
<blockquote>
<p>The complete project is avaiable on <a target="_blank" href="https://github.com/mkonkel/GameShop">GitHub</a></p>
</blockquote>
<hr />
<h2 id="heading-configuring-the-backend-for-the-applications"><strong>Configuring the backend for the applications.</strong></h2>
<p>Firstly, we should start by adding some basic routing to ensure that everything is functioning correctly. Since we are building a GameShop application, one of the most critical endpoints will be the one that allows us to fetch all available games from our database. To achieve this, we need to configure the appropriate endpoint in our routing module.</p>
<p>Begin by defining a route that handles GET requests for fetching the list of games. This route will interact with our backend service to retrieve the game data and return it to the client in a structured format, such as JSON. Here is a simple example of how to set up this endpoint in KTOR:</p>
<p><code>Application.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">module</span><span class="hljs-params">()</span></span> { 
    configureRouting() 
}
</code></pre>
<p><code>Routing.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureRouting</span><span class="hljs-params">()</span></span> { 
    install(Routing) 

    routing { 
        gamesRouting() 
    } 
}
</code></pre>
<p><code>GamesRoutes.kt</code></p>
<pre><code class="lang-kotlin">GamesRoutes.kt

<span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">gamesRouting</span><span class="hljs-params">()</span></span> { 
    route(<span class="hljs-string">"/games"</span>) { 
        <span class="hljs-keyword">get</span> { 
            call.respondText(text = <span class="hljs-string">"There are no games in our shop yet..."</span>, status=HttpStatusCode.OK) 
        } 
    } 
}
</code></pre>
<p>We have established the most basic form of routing, ensuring that our server is operational and capable of delivering a placeholder response. This initial setup is crucial as it lays the foundation for more complex functionalities. By defining a simple GET endpoint, we can confirm that our routing configuration is correct and that the server can handle incoming requests without any issues.</p>
<p><img src="https://speednetsoftware.com/app/uploads/2024/05/Zrzut-ekranu-2024-05-7-o-14.07.46-1024x336.png" alt /></p>
<p>Now we need to think about how to utilize as much as possible from the <strong>KMM</strong> approach and be able to share as much code as possible with the backend and frontend applications. In general, our goal at this point is to use the same domain models and the same repositories (but with different implementations). I will create the domain and the repository as separate modules.</p>
<p>The <code>shared/commonMain</code> module will be designed to serve the frontend applications. This module will be responsible for implementing the domain models and the repository interfaces. Additionally, it will include a common HTTP client that can be used across all platforms, ensuring consistency and reducing redundancy in code.</p>
<p>The <code>server</code> module will be responsible for implementing the domain models and the repository interfaces. Unlike the frontend applications, which will use the <code>shared/commonMain</code> module, the <code>server</code> module will provide its own unique implementations of these interfaces. This means that while the frontend and backend will share the same domain models and repository interfaces, the actual logic for data retrieval and manipulation will differ between the two. The <code>server</code> module will handle backend-specific tasks such as database interactions, server-side processing, and business logic executio</p>
<p><img src="https://speednetsoftware.com/app/uploads/2024/05/Zrzut-ekranu-2024-05-7-o-14.08.47-1024x532.png" alt /></p>
<p><img src="https://speednetsoftware.com/app/uploads/2024/05/Zrzut-ekranu-2024-05-7-o-14.09.06-1024x497.png" alt /></p>
<p><code>Game.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Game</span></span>( 
    <span class="hljs-keyword">val</span> name: String 
)
</code></pre>
<p><code>GamesRepository.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">GamesRepository</span> </span>{ 
    <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getGames</span><span class="hljs-params">()</span></span>: List&lt;Game&gt; 
}
</code></pre>
<p>The backend will implement <code>GamesRepository</code> as <code>DatabaseGamesRepository</code> using <code>H2 Database</code>, while the apps will implement this repository as <code>HttpGamesRepository</code> and use the KTOR client to communicate with the server. This approach allows for good code separation and a significant amount of common code that can be widely used in the application.</p>
<p>We can start by creating the <code>RealDatabaseGamesRepository</code>. This class will implement the common <code>GamesRepository</code> interface but will interact with the database through the <code>GamesDAOFacade</code>. The <code>GamesDAOFacade</code> will serve as an abstraction layer, allowing us to perform database operations without exposing the underlying database implementation details. By doing so, we ensure that our repository remains decoupled from the specific database technology being used, making it easier to switch databases or update the database schema in the future. Additionally, this setup promotes better testability, as we can mock the <code>GamesDAOFacade</code> during unit testing to simulate various database behaviors and edge cases.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RealDatabaseGamesRepository</span></span>( 
<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> dao: GamesDAOFacade 
) : GamesRepository { 
    <span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getGames</span><span class="hljs-params">()</span></span>: List&lt;Game&gt; = dao.getGames() 
}
</code></pre>
<p>If you want to know more about <code>DI</code> and <code>Database</code> in <strong>KTOR</strong> the full description is <a target="_blank" href="https://hashnode.com/post/clyibnsbi000e08l8g4bc4kzy">here</a>.</p>
<p>We can now proceed to inject the repository into the routing mechanism of our application. By doing this, we enable our application to handle HTTP requests effectively. When a request is made to fetch game data, the routing will utilize the injected repository to retrieve the necessary information from the database. This approach ensures that our routing logic remains clean and focused on handling HTTP requests and responses, while the repository takes care of the data retrieval and manipulation.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">gamesRouting</span><span class="hljs-params">()</span></span> { 
    <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;GamesRepository&gt;() 
       <span class="hljs-keyword">get</span>&lt;GamesResources&gt; { 
          <span class="hljs-keyword">val</span> games = repo.getGames() 

            call.respond( 
                status = HttpStatusCode.OK, 
                message = games, 
            ) 
        } 
}
</code></pre>
<p>Following up on the KTOR <a target="_blank" href="https://hashnode.com/post/clyi7m44j000308mh9gza6jww">blog post</a> we will add: </p>
<ul>
<li><p>JWT authentication</p>
</li>
<li><p>Administrator role</p>
</li>
<li><p>Login functionality</p>
</li>
<li><p>Game management endpoints</p>
</li>
<li><p>Orders endpoint </p>
</li>
</ul>
<blockquote>
<p>These topics will not be covered in this article as they can be found in the mentioned link.</p>
</blockquote>
<hr />
<h2 id="heading-enhancements">Enhancements</h2>
<h3 id="heading-roles">Roles</h3>
<p>To make this application a bit more interesting, we can add <strong>ROLES</strong> to users and then show or hide some functionalities on the frontend. For example, users will only be able to fetch games, but the administrator will be able to manage them. With this approach, we can create an MVP for content management. To do so, we need to implement roles. We can start with the shared domain object, the roles table, and a relation between users and roles.</p>
<p><code>domain/Role.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span> 
<span class="hljs-keyword">enum</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Role</span> </span>{ 
    ADMIN, 
    USER, 
}
</code></pre>
<p><code>domain/User.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span> 
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>( 
    <span class="hljs-keyword">val</span> id: String, 
    <span class="hljs-keyword">val</span> name: String, 
    <span class="hljs-keyword">val</span> username: String, 
    <span class="hljs-keyword">val</span> role: Role, 
) 

<span class="hljs-meta">@Serializable</span> 
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRequest</span></span>( 
    <span class="hljs-keyword">val</span> name: String, 
    <span class="hljs-keyword">val</span> username: String, 
    <span class="hljs-keyword">val</span> password: String, 
)
</code></pre>
<p><code>server/Roles.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> Roles : IntIdTable() { 
    <span class="hljs-keyword">val</span> name = varchar(<span class="hljs-string">"name"</span>, <span class="hljs-number">128</span>) 
}
</code></pre>
<p><code>server/Users.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> Users : UUIDTable() { 
    ... 
    <span class="hljs-keyword">val</span> role = reference(<span class="hljs-string">"role_id"</span>, Roles, onDelete = ReferenceOption.CASCADE).index() 
}
</code></pre>
<p>The <code>Users</code> table has been extended with the <strong>role</strong> property, which establishes a relationship with the roles table. This addition allows us to assign specific roles to users, such as <code>ADMIN</code> or <code>USER</code>, enhancing the application's functionality by enabling role-based access control. To achieve this, we need to adhere to the guidelines provided by <strong>Exposed</strong> for creating Data Access Objects (DAOs). This involves refactoring existing classes and repositories to ensure they align with the new structure.</p>
<p>For accurate relation mapping between users and roles, we should utilize <code>Entities</code> that represent the actual rows in the database. This approach ensures that our data model accurately reflects the underlying database schema, making it easier to manage and query the data. To implement these changes, we will need to update our domain models and database schema. We will modify the <code>User</code> class to include a reference to the <code>Role</code> class. For more detailed information on how to create and manage DAOs with Exposed, you can refer to the official documentation <a target="_blank" href="https://github.com/JetBrains/Exposed/wiki/DAO">here</a>.</p>
<p><code>Roles.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RoleEntity</span></span>(id: EntityID&lt;<span class="hljs-built_in">Int</span>&gt;) : IntEntity(id) { 
    <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> : IntEntityClass&lt;RoleEntity&gt;(Roles) 

    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">by</span> Roles.name 
}
</code></pre>
<p><code>Users.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserEntity</span></span>(id: EntityID&lt;UUID&gt;) : UUIDEntity(id) {  
   <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> : UUIDEntityClass&lt;UserEntity&gt;(Users) 

    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">by</span> Users.name 
    <span class="hljs-keyword">var</span> date_created <span class="hljs-keyword">by</span> Users.date_created 
    <span class="hljs-keyword">var</span> username <span class="hljs-keyword">by</span> Users.username 
    <span class="hljs-keyword">var</span> password <span class="hljs-keyword">by</span> Users.password 
    <span class="hljs-keyword">var</span> role <span class="hljs-keyword">by</span> RoleEntity referencedOn Users.role 
}
</code></pre>
<p>Since we will now operate on the entities, the <code>DAOFacade</code> need to be adjusted accordingly. Instead of directly interacting with the database tables, we will perform all operations through the newly introduced <strong>entity objects</strong>.</p>
<p>First, we need to refactor the existing DAOFacade classes to replace any direct table access with entity-based operations. This involves updating the methods to use the entity objects for querying and manipulating data. For example, instead of writing a SQL query to fetch user data, we will use the <code>UserEntity</code> class to retrieve the user information. Similarly, for creating a new user, we will use the <code>UserEntity</code> class to insert the new record into the database.</p>
<p><code>RealUsersDAOFacade.kt</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createUser</span><span class="hljs-params">(userRequest: <span class="hljs-type">UserRequest</span>)</span></span> = dbQuery { 
    <span class="hljs-keyword">val</span> userRoleId = requireNotNull(rolesDAOFacade.getIdByRole(Role.USER)) 

    UserEntity.new { 
        name = userRequest.name 
        username = userRequest.username 
        password = userRequest.password 
        date_created = Clock.System.now().toLocalDateTime(TimeZone.UTC).date.toString() 
        role = RoleEntity[userRoleId] 
    }.toUser() 
} 

<span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsers</span><span class="hljs-params">()</span></span>: List&lt;User&gt; = dbQuery { 
    UserEntity.all().map { it.toUser() } 
}
</code></pre>
<p>In summary, the transition to using entity objects for all database operations will streamline our data access logic, making it more consistent and easier to work with.</p>
<h3 id="heading-role-based-authentication">Role-based authentication</h3>
<p>Once roles are implemented, the final step is to secure our routes effectively. With the <code>JWT</code>, we have ensured that our user is authenticated. Now, the <strong>roles</strong> will help us authorize the calls appropriately. To achieve this, we will add the role information to the JWT token. This way, each token will carry the user's role, allowing us to check permissions easily.</p>
<p>To integrate this into our application, we can create a custom <code>KTOR</code> plugin. This plugin will intercept incoming requests and verify the user's role against the required permissions for the route. If the user has the necessary role, the request will proceed; otherwise, it will be rejected with an appropriate error message.</p>
<blockquote>
<p>If you want to read more about custom plugins, please check the <a target="_blank" href="https://ktor.io/docs/custom-plugins.html#databases">docs</a></p>
</blockquote>
<p>Adding the role to the <code>JWT</code> is a straightforward process. We will include the role information in the same section where we currently add the userId. This involves modifying the <code>JWT</code> creation logic to append the user's role alongside their unique identifier. By doing so, each token will carry both the userId and the role, ensuring that we have all the necessary information to authenticate and authorize users effectively.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> token = JWT.create()   
 … 
 .withClaim(<span class="hljs-string">"userId"</span>, it.id) 
 .withClaim(<span class="hljs-string">"role"</span>, listOf(it.role.name))   
 …
</code></pre>
<p>The plugin will rely on an authentication hook, which means that the code inside this hook will be executed after the user has been authenticated. From the authenticated call, we can easily obtain the decrypted JWT payload. By extracting the value of the role property from the payload, we can determine the user's permissions.</p>
<p>Next, we will create an extension function for the <code>Route</code> class. This extension function will be invoked with every endpoint call. The function will be called with a set of roles that are allowed to access a given endpoint. By doing this, we ensure that each endpoint specifies which roles are permitted to access it. The function will then install the authorization plugin and pass the required roles to it..</p>
<p>Finally, we can create a custom exception that will be thrown whenever an authorization error occurs. This custom exception will provide a clear and consistent way to handle authorization failures. By throwing this exception, we can ensure that users receive appropriate error messages when they attempt to access endpoints.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthorizationException</span></span>( 
    route: String, 
    <span class="hljs-keyword">val</span> reasons: List&lt;String&gt;, 
) : IllegalArgumentException(<span class="hljs-string">"You don`t have access to <span class="hljs-variable">$route</span>. Reasons: <span class="hljs-subst">${reasons.joinToString()}</span>"</span>)
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthorizationConfiguration</span> </span>{ 
    <span class="hljs-keyword">val</span> requiredRoles: MutableSet&lt;Role&gt; = mutableSetOf() 

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">roles</span><span class="hljs-params">(roles: <span class="hljs-type">Set</span>&lt;<span class="hljs-type">Role</span>&gt;)</span></span> { 
        requiredRoles.addAll(roles) 
    } 
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">val</span> RoleAuthorizationPlugin = 
    createRouteScopedPlugin(<span class="hljs-string">"RoleAuthorizationPlugin"</span>, ::AuthorizationConfiguration) { 
        on(AuthenticationChecked) { call -&gt; 
            <span class="hljs-keyword">val</span> principal = call.principal&lt;JWTPrincipal&gt;() ?: <span class="hljs-keyword">return</span><span class="hljs-symbol">@on</span> 
            <span class="hljs-keyword">val</span> roles = 
                principal 
                    .payload 
                    .getClaim(<span class="hljs-string">"role"</span>) 
                    .asList(String::<span class="hljs-keyword">class</span>.java) 
                    .map { Role.valueOf(it) } 

            <span class="hljs-keyword">if</span> (pluginConfig.requiredRoles.isNotEmpty() &amp;&amp; roles.intersect(pluginConfig.requiredRoles).isEmpty()) { 
                <span class="hljs-keyword">throw</span> AuthorizationException( 
                    route = call.request.path(), 
                    reasons = listOf(<span class="hljs-string">"You don`t have required role"</span>), 
                ) 
            } 
        } 
    }
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">withRole</span><span class="hljs-params">( 
    <span class="hljs-keyword">vararg</span> roles: <span class="hljs-type">Role</span>, 
    build: <span class="hljs-type">Route</span>.() -&gt; <span class="hljs-type">Unit</span>, 
)</span></span> { 
    <span class="hljs-keyword">val</span> route = 
        createChild( 
            <span class="hljs-keyword">object</span> : RouteSelector() { 
                <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">evaluate</span><span class="hljs-params">( 
                    context: <span class="hljs-type">RoutingResolveContext</span>, 
                    segmentIndex: <span class="hljs-type">Int</span>, 
                )</span></span>: RouteSelectorEvaluation { 
                    <span class="hljs-comment">// Transparent selector means that it does not consume anything from the URL, so child routes can match. </span>
                    <span class="hljs-keyword">return</span> RouteSelectorEvaluation.Transparent 
                } 
            }, 
        ) 

    route.install(RoleAuthorizationPlugin) { 
        roles(roles.toSet()) 
    } 

    route.build() 
}
</code></pre>
<p>There is nothing more left to do but to apply the freshly created plugin to our routes. Let's update the users' routing to include this new plugin. By doing this, we ensure that only users with the appropriate roles can access certain routes. This adds an extra layer of security and control over who can perform specific actions within our application. Here's how we can update the users' routing to incorporate the role-based authorization plugin:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">usersRouting</span><span class="hljs-params">()</span></span> { 
    <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;DatabaseUsersRepository&gt;() 

    authenticate(<span class="hljs-string">"jwt-auth"</span>) { 
        withRole(Role.ADMIN) { 
            route(“/users”) { 
      } 
    } 
}
</code></pre>
<p>With everything set up, we can test it with HTTP requests from the <code>LoginRequests.http</code> test. If we try to request users from an account other than admin, we should see the proper message:</p>
<pre><code class="lang-kotlin">GET http:<span class="hljs-comment">//0.0.0.0:8080/users </span>

HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">401</span> Unauthorized 

You don`t have required role
</code></pre>
<p>The last thing that needs to be done is returning the <strong>role</strong> to the clients.</p>
<blockquote>
<p>By providing the role to the frontend application, we can show different UI elements, restrict access to certain screens, and control functionalities based on the user's role.</p>
</blockquote>
<p>To achieve that we need to add the <code>User</code> property to the <code>LoginResponse.</code> When we are creating the login response, we already have the user data fetched from the DB.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span> 
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginResponse</span></span>( 
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"token"</span>)</span> 
    <span class="hljs-keyword">val</span> token: String, 
    <span class="hljs-meta">@SerialName(<span class="hljs-meta-string">"user"</span>)</span> 
    <span class="hljs-keyword">val</span> user: User, 
)
</code></pre>
<hr />
<p>Our backend is up and running with basic functionalities. Now we need to switch our focus to the front-end applications. In the next blog post, I will add the KTOR client to the shared module that can be used by front-end applications (Android, iOS, and Web).</p>
<blockquote>
<p>This article provides a comprehensive guide to setting up routing for a GameShop application using KTOR, incorporating domain models, repositories, and role-based authorization. It covers the initial configuration of routing to fetch games, the creation of shared and server-specific modules for domain models, implementing repositories with database interactions, and integrating JWT authentication with role-based access control. Additionally, it details how to update data access logic to utilize entity objects and how to enable role-based authorization in the backend to enhance security and functionality. Future posts will address integrating the KTOR client into front-end applications.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Complete Guide to Becoming a Fullstack Kotlin Developer - project setup]]></title><description><![CDATA[Guide to setting up a Compose Multiplatform project for fullstack development covering Android, iOS, Web, and backend integration]]></description><link>https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-project-setup</link><guid isPermaLink="true">https://michalkonkel.dev/complete-guide-to-becoming-a-fullstack-kotlin-developer-project-setup</guid><category><![CDATA[compose multiplatform]]></category><category><![CDATA[Kotlin Multiplatform]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[ktor]]></category><category><![CDATA[fullstack]]></category><category><![CDATA[Cross Platform App Development. ]]></category><category><![CDATA[Kotlin]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Thu, 01 Feb 2024 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720844708889/1ed9c3be-85d7-4e01-8dd6-b15988fb723f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When perusing job listings, you’ll often come across the ubiquitous phrase “Fullstack developer wanted.” If you are a mobile developer with a good <a target="_blank" href="https://speednet.pl/kotlin-multiplatform-expectations-vs-reality-for-ios-and-android/">Kotlin background</a>, you are about one step away from becoming a full-stack Kotlin developer. That superpower is at your fingertips, so grab it!</p>
<p>In this blog series, I would like to show you how to create a Kotlin multiplatform project based on Compose Multiplatform that will share common business logic and UI with Android, iOS, and Web applications. Moreover, we will use the same shared business logic on the backend side of our KTOR application. We can share API interfaces, domain objects, validation rules, and more!</p>
<p>So… as everyone knows, the beginnings can be tough, but the results of your work will be absolutely astonishing! Let me guide you through the project setup that will be our foundation for amazing future development.</p>
<blockquote>
<p>The complete project is avaiable on <a target="_blank" href="https://github.com/mkonkel/GameShop">GitHub</a></p>
</blockquote>
<h2 id="heading-lets-start-from-scratch"><strong>Let’s start from scratch…</strong></h2>
<p>… and use the project configuration wizard from <a target="_blank" href="https://kmp.jetbrains.com/">JetBrains</a>. Check Android, iOS, and Backend, fill in the project name and ID, and click download. Run this project from the latest version of Android Studio or IntelliJ.</p>
<p><img src="https://speednet.pl/app/uploads/2024/01/Screenshot-2024-01-30-at-05.35.08-526x1024.png" alt /></p>
<p>In our Kotlin Multiplatform project, we need to use the latest <code>compose-plugin</code> with warm support, which is still experimental (at the time of writing this blog post, the most recent version is <code>1.6.0-alpha01</code>). Add it to the project and sync it. The compose plugin version is in the <strong>gradle</strong> folder in the <strong>libs.versions.toml</strong>, where all dependencies are located.</p>
<p>While the project is syncing, we can inspect the generated template. It is divided into two main sections: <strong>shared</strong> and <strong>composeApp.</strong> ComposeApp is for the code holding our applications’ Compose Multiplatform code (mostly UI).</p>
<p>These subfolders correspond to the targets for which we will be launching the application:</p>
<ul>
<li><p><strong>commonMain</strong> is shared code for all platforms</p>
</li>
<li><p><strong>IosMain</strong> is for iOS-specific code e.g. apple cryptography</p>
</li>
<li><p><strong>androidMain</strong> is for Android code</p>
</li>
<li><p><strong>WasmJsMain</strong> is for WebAssembly code</p>
</li>
</ul>
<p>The same rules apply to the <strong>shared</strong> module where we will hold our business/domain logic, API requests, and responses, or even the HTTP client. If there is a need to add specific behaviors depending on the platform, we can also use some of the generated subfolders.</p>
<p>The server module is a place where the KTOR backend application is located. It is independent and does not use code from <strong>composeApp</strong> or <strong>shared</strong>. If we properly structure our code with some additional modules, then we can share part of it even with the backend application (for example, some API models).</p>
<p><strong>Last but not least…</strong></p>
<p>… is the iOSApp module, which contains an iOS application. It’s an entry point for running the application on Apple devices and a place for the <strong>SwiftUI</strong> code to be added (if needed).</p>
<p><img src="https://speednet.pl/app/uploads/2023/12/Screenshot-2023-11-16-at-21.59.09-2.png" alt /></p>
<p><img src="https://speednet.pl/app/uploads/2023/12/Screenshot-2023-11-16-at-21.59.21-3.png" alt /></p>
<p><strong>Customizing the Web run</strong></p>
<p>We can add one thing in the <strong>composeApp</strong><code>build.gradle.kts</code> that will run our desired browser for the wasm application; we need to locate the <strong>wasmJs</strong> code block and add Google Chrome dev (or another browser) as a starting point.</p>
<pre><code class="lang-kotlin">wasmJs { 
    moduleName = “gameshopwasmapp” 
    browser { 
        commonWebpackConfig { 
            outputFileName = “gameshopwasmapp.js” 
            devServer = (devServer ?: KotlinWebpackConfig.DevServer()).apply { 
                <span class="hljs-keyword">open</span> = mapOf( 
                    “app” to mapOf( 
                        “name” to “google chrome dev” 
                    ) 
                ) 
            } 
        } 
    } 
    binaries.executable() 
}
</code></pre>
<p>Before launching the WASM application, we need to enable its support in our browser. Please follow these <a target="_blank" href="https://kotlinlang.org/docs/wasm-get-started.html#troubleshooting">instructions</a>.</p>
<p>Now, we can use the <code>./gradlew :composeApp:wasmJsBrowserDevelopmentRun</code> command to run our application in the browser. To run the <strong>Android</strong> and <strong>iOS</strong> apps, you must start the appropriate Android Studio configurations.</p>
<p>If everything goes well, you can see something like this: click the button to see how the UI changes</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720845957286/35c5d74a-c0cf-42ee-961d-85096d0cb860.gif" alt class="image--center mx-auto" /></p>
<p>Running the generated project was straightforward. We almost did nothing to make it run. This is a great point to start your project. Get benefits from writing code once and covering three platforms. In the next post, we will add some code to the backend application based on my previous post about the <a target="_blank" href="https://hashnode.com/post/clyichel900030al14zpe4e4i">KTOR</a> – we will extend the existing GameShop with the mobile and frontend applications.</p>
<p>In the following articles, I will dive deep into the KTOR Server and Client setup for our application. We will explore the app architecture using the Decompose library, which helps in managing the lifecycle and state of our components efficiently. Additionally, we will cover the Compose Multiplatform UI, which allows us to create beautiful and responsive user interfaces for client applications across different platforms. We will provide step-by-step guides, code snippets, and best practices to ensure you can implement these features seamlessly.</p>
<p>Stay tuned!</p>
]]></content:encoded></item><item><title><![CDATA[KTOR as a backend - part 3]]></title><description><![CDATA[Learn how to implement JWT authentication and validation in your KTOR-based REST backend for a secure and reliable game shop application]]></description><link>https://michalkonkel.dev/ktor-as-a-backend-part-3</link><guid isPermaLink="true">https://michalkonkel.dev/ktor-as-a-backend-part-3</guid><category><![CDATA[ktor]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[backend]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Wed, 16 Nov 2022 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720766940532/6b4b0e52-5c07-493b-9e5b-44ac8f496515.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post, we will delve into the process of adding authentication and validation to our REST backend for the game shop. We will walk through the steps of implementing authentication using JWT (JSON Web Tokens), including how to generate tokens and verify them.</p>
<p>Next, we will cover validation. We will demonstrate how to use validation rules on our API endpoints. By the end of this post, you will have a comprehensive understanding of how to secure and validate your REST backend, making it robust and reliable for handling user data in our game shop.</p>
<h1 id="heading-authentication-users-endpoint"><strong>Authentication — users endpoint</strong></h1>
<p>With all the good things we have put into our project so far, another thing is worth mentioning — how to protect some endpoints against unrestricted access. All modern frameworks got some out-of-the-box solutions, and the same is with <a target="_blank" href="https://ktor.io/docs/authentication.html">KTOR</a> — from the mobile developer’s point of view, the most common case is authentication with some token. We will add the <a target="_blank" href="https://jwt.io/">JSON Web Token</a> authentication for our game shop.</p>
<p>The flow here is simple: the user needs to request some public endpoint with username/password if credentials are valid, the severe will respond with the token, then the token must be included in the header. The server verifies the token when a user tries to access secured resources.</p>
<pre><code class="lang-kotlin">implementation(<span class="hljs-string">"io.ktor:ktor-server-auth:<span class="hljs-variable">$ktor_version</span>"</span>)
implementation(<span class="hljs-string">"io.ktor:ktor-server-auth-jwt:<span class="hljs-variable">$ktor_version</span>"</span>)
</code></pre>
<p>With the flow described above, we need to create a public login endpoint with a request and response.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginRequest</span></span>(
   <span class="hljs-keyword">val</span> username: String,
   <span class="hljs-keyword">val</span> password: String
)

<span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginResponse</span></span>(
   <span class="hljs-keyword">val</span> token: String
)

<span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">loginRouting</span><span class="hljs-params">()</span></span> {
   <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;UsersRepository&gt;()

   route(<span class="hljs-string">"/login"</span>) {
       post {
              …
           )
       }
   }
</code></pre>
<p>The JWT plugin needs to be installed and configured. When creating the token, we will check if provided user and password are correct (and the user exists in the database), then we will put the <code>userId</code> into the JWT claim (the payload), so it can be accessed while requesting secured paths, we also need to configure an expiration date. We provide some additional info such as <code>secret</code>, <code>audience</code><strong>,</strong> <code>issuer</code> and <code>realm</code> (all of them are explained in the <a target="_blank" href="https://www.rfc-editor.org/rfc/rfc7519">JWT RFC</a>).</p>
<p>If a user exists, we will respond with a valid JWT token, if not, we will send a <code>400 Bad Request</code>. Because JWT is ready to use, the standalone implementation, we don’t need to bother by storing the created tokens with users — the token is valid as long as the expiration period, or as long the <strong>SECRET</strong> stays unchanged — there is no way to revoke created tokens.</p>
<p>The configuration properties</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> SECRET = <span class="hljs-string">"SECRETT"</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> AUDIENCE = <span class="hljs-string">"http://0.0.0.0:8080"</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> ISSUER = <span class="hljs-string">"http://0.0.0.0:8080/login"</span>


The /login endpoint implementation

<span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">loginRouting</span><span class="hljs-params">()</span></span> {
   <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;UsersRepository&gt;()

   route(<span class="hljs-string">"/login"</span>) {
       post {
           <span class="hljs-keyword">val</span> loginRequest = call.receive&lt;LoginRequest&gt;()

           repo.getUserByUsernameAndPassword(loginRequest.username, loginRequest.password)
               ?.let {
                   <span class="hljs-keyword">val</span> token = JWT.create()
                       .withAudience(AUDIENCE)
                       .withIssuer(ISSUER)
                       .withClaim(<span class="hljs-string">"userId"</span>, it.id)
                       .withExpiresAt(Date(Clock.System.now().toEpochMilliseconds() + <span class="hljs-number">60000</span>))
                       .sign(Algorithm.HMAC256(SECRET))
                   call.respond(LoginResponse(token))
               } ?: call.respondText(
               status = HttpStatusCode.BadRequest,
               text = <span class="hljs-string">"Invalid login or password"</span>
           )
       }
   }
}
</code></pre>
<p>The <code>getUserByUsernameAndPassword</code> method is implemented in the <code>UsersDAOFacadeImpl</code><strong>,</strong> and it’s pretty simple.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUserByUsernameAndPassword</span><span class="hljs-params">(username: <span class="hljs-type">String</span>, password: <span class="hljs-type">String</span>)</span></span>: User? = dbQuery {
   Users.select { (Users.username eq username) and (Users.password eq password) }
       .limit(<span class="hljs-number">1</span>)
       .firstOrNull()
       ?.toUser()
}
</code></pre>
<p>Now we are able to obtain a token. The next step is to validate it with every incoming request. To do so, we need to install the authentication plugin and configure the token verifier. Let’s create another extension function that we can put in our <code>Application.kt</code>.</p>
<pre><code class="lang-kotlin">install(Authentication) {
       jwt(<span class="hljs-string">"jwt-auth"</span>) {
           realm = <span class="hljs-string">"GameShopAccess"</span>
           verifier(
               JWT
                   .require(Algorithm.HMAC256(SECRET))
                   .withAudience(AUDIENCE)
                   .withIssuer(ISSUER)
                   .build()
           )

           validate { jwtCredential -&gt;
               jwtCredential.payload.claims[<span class="hljs-string">"userId"</span>]?.asString()
                   ?.let {
                       <span class="hljs-keyword">if</span> (userRepository.existById(it)) {
                           JWTPrincipal(jwtCredential.payload)
                       } <span class="hljs-keyword">else</span> {
                           <span class="hljs-literal">null</span>
                       }
                   }
           }

           challenge { _, _ -&gt;
               call.respond(HttpStatusCode.Unauthorized, <span class="hljs-string">"Token is not valid or has expired!"</span>)
           }
       }
   }
}
</code></pre>
<p>The first thing that is checked is the token format and signature. If it’s invalid, the <strong>challenge</strong> lambda is fired, and the user is unauthorized, with proper HTTP code. The <strong>verifier</strong> block is responsible for these checks.</p>
<p>The <strong>validate</strong> lambda happens after the <strong>verify</strong> block, and it can access the token payload where in the <code>/login</code> method, we put the <strong>userId.</strong> So the validation will be really simple — we just check if a user with a given <code>id</code> exists in our database — if yes, we can proceed with the request.</p>
<p>The last thing is to use created authentication with desired endpoints — let’s assume that creating new users should be restricted to logged-in users only. This is simple as just adding the <code>authenticate()</code> function on the routes we want to protect.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">usersRouting</span><span class="hljs-params">()</span></span> {
   <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;UsersRepository&gt;()

   authenticate(<span class="hljs-string">"jwt-auth"</span>) {
       route(<span class="hljs-string">"/users"</span>) {
           post {
             …
               )
           }

           <span class="hljs-keyword">get</span> {
             …
           }
</code></pre>
<p>From now on, when we try to access the list of users without a valid token, we will receive an error.</p>
<pre><code class="lang-kotlin">### GET List of the users
GET http:<span class="hljs-comment">//0.0.0.0:8080/users</span>
Content-Type: application/json

http:<span class="hljs-comment">//0.0.0.0:8080/users</span>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">401</span> Unauthorized
Content-Length: <span class="hljs-number">34</span>
Content-Type: text/plain; charset=UTF-<span class="hljs-number">8</span>
Connection: keep-alive
</code></pre>
<p>The token is not valid or has expired!</p>
<p>We can obtain a valid token by calling the login method and storing the received token for further requests.</p>
<pre><code class="lang-kotlin">### POST login and retrieve a token
POST http:<span class="hljs-comment">//0.0.0.0:8080/login</span>
Content-Type: application/json

{
 <span class="hljs-string">"username"</span>: <span class="hljs-string">"admin"</span>,
 <span class="hljs-string">"password"</span>: <span class="hljs-string">"pass"</span>
}

&gt; {%
   client.test(<span class="hljs-string">"Assert token is retrieved"</span>, function() {
     client.assert(response.body.token !== <span class="hljs-string">""</span>)
   })

   client.global.<span class="hljs-keyword">set</span>(<span class="hljs-string">"auth_token"</span>, response.body.token);
%}
</code></pre>
<p>But unfortunately, calling this method will return <strong>400 Bad Request Invalid login or password</strong> because the required user does not exist in our database. There is a simple solution for that — we need to pre-populate the database with some users (please note that before adding a user to the database when the table is created, we should first check if such a user is not already in our DB)</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">object</span> SchemaDefinition {
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createSchema</span><span class="hljs-params">()</span></span> {
       transaction {

           Users.insert {
               it[name] = <span class="hljs-string">"Admin"</span>
               it[username] = <span class="hljs-string">"admin"</span>
               it[password] = <span class="hljs-string">"pass"</span>
               it[date_created] = Clock.System.now().toLocalDateTime(TimeZone.UTC).date.toString()
           }
       }
   }
}
</code></pre>
<p>So from now on, we need to add a JWT token to the header in every request.</p>
<pre><code class="lang-kotlin">### GET List of the users
GET http:<span class="hljs-comment">//0.0.0.0:8080/users</span>
Content-Type: application/json
Authorization: Bearer {{auth_token}}

http:<span class="hljs-comment">//0.0.0.0:8080/users</span>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">200</span> OK
Content-Length: <span class="hljs-number">321</span>
Content-Type: application/json
Connection: keep-alive

[
  {
    <span class="hljs-string">"id"</span>: <span class="hljs-string">"c96ae8c1-e85e-4fd0-b54d-46e1f2a66983"</span>,
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Admin"</span>,
    <span class="hljs-string">"username"</span>: <span class="hljs-string">"admin"</span>
  }
]
</code></pre>
<h1 id="heading-validation-users-endpoint"><strong>Validation — users endpoint</strong></h1>
<p>There is one thing left until we consider our GameShop ready — data validation. In many cases, we need to check if the data we receive from clients is valid. In terms of adding new user we can add some of the following validations</p>
<ul>
<li><p>username and password can’t be empty</p>
</li>
<li><p>username, password, and name must be at least 5 characters long</p>
</li>
<li><p>username should be unique</p>
</li>
</ul>
<p>As you probably expected, the KTOR got a plugin just for that, let’s install the <strong>RequestValidation</strong>.</p>
<pre><code class="lang-kotlin">implementation(<span class="hljs-string">"io.ktor:ktor-server-request-validation:<span class="hljs-variable">$ktor_version</span>"</span>)
</code></pre>
<p>The KTOR plugins may be installed to the <strong>Application</strong> and the specific <strong>Routes</strong> — in our case, we will do it in the <code>/users</code> endpoint.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">usersRouting</span><span class="hljs-params">()</span></span> {
   <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;UsersRepository&gt;()

   authenticate(<span class="hljs-string">"jwt-auth"</span>) {
       route(<span class="hljs-string">"/users"</span>) {
           install(RequestValidation) {
               validate&lt;UserRequest&gt; { request -&gt;
                   <span class="hljs-keyword">when</span> {
                       request.password.isBlank() -&gt; ValidationResult.Invalid(<span class="hljs-string">"Password is required!"</span>)
                       request.username.isBlank() -&gt; ValidationResult.Invalid(<span class="hljs-string">"Username is required!"</span>)
                       request.password.length &lt; <span class="hljs-number">5</span> -&gt; ValidationResult.Invalid(<span class="hljs-string">"Password is too short!"</span>)
                       request.name.length &lt; <span class="hljs-number">5</span> -&gt; ValidationResult.Invalid(<span class="hljs-string">"Name is too short!"</span>)
                       request.username.length &lt; <span class="hljs-number">5</span> -&gt; ValidationResult.Invalid(<span class="hljs-string">"Username is too short!"</span>)
                       repo.existByName(request.username) -&gt; ValidationResult.Invalid(<span class="hljs-string">"User already exists!"</span>)
                       <span class="hljs-keyword">else</span> -&gt; ValidationResult.Valid
                   }
               }
           }
           post {
               <span class="hljs-keyword">val</span> request = call.receive&lt;UserRequest&gt;()
               <span class="hljs-keyword">val</span> user = repo.addUser(request)

               requireNotNull(user)

               call.respond(
                   status = HttpStatusCode.Created,
                   message = user
               )
           }
       }
   }
}
</code></pre>
<p>As you can see, we are able to call our database directly in the validate lambda. If the request is valid, the server will proceed with the request handling, if not, the <strong>RequestValidationException</strong> will be thrown. The application will respond with 500 HTTP codes. But this is not something we want, the errors should be handled gracefully with proper error codes and some explanation.</p>
<p>We can use the <a target="_blank" href="https://ktor.io/docs/status-pages.html"><strong>StatusPages</strong></a> to achieve such a goal, which can take care of any exception in our code. The usage and configuration are straightforward.</p>
<pre><code class="lang-kotlin">implementation(<span class="hljs-string">"io.ktor:ktor-server-status-pages:<span class="hljs-variable">$ktor_version</span>"</span>)
<span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureStatusPages</span><span class="hljs-params">()</span></span> {
   install(StatusPages) {
       exception&lt;Throwable&gt; { call, cause -&gt;
           <span class="hljs-keyword">when</span> (cause) {
               <span class="hljs-keyword">is</span> RequestValidationException -&gt;
                   call.respondText(status = HttpStatusCode.BadRequest, text = cause.reasons.joinToString())

               <span class="hljs-keyword">else</span> -&gt;
                   call.respondText(status = HttpStatusCode.InternalServerError, text = <span class="hljs-string">"500: <span class="hljs-variable">$cause</span>"</span>)
           }
       }
   }
}
</code></pre>
<p>In case of any RequestValidationException, we will return a 400 BadRequest with a reason, any other issues will still be mapped to 500 Internal Server Error.</p>
<p>Let’s try to add a user with a too-short password.</p>
<pre><code class="lang-kotlin">### POST create a new user
POST http:<span class="hljs-comment">//0.0.0.0:8080/users</span>
Content-Type: application/json
Authorization: Bearer {{auth_token}}

{
 <span class="hljs-string">"name"</span>: <span class="hljs-string">"Test User"</span>,
 <span class="hljs-string">"username"</span>: <span class="hljs-string">"tst"</span>,
 <span class="hljs-string">"password"</span>: <span class="hljs-string">"password"</span>
}

http:<span class="hljs-comment">//0.0.0.0:8080/users</span>
HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">400</span> Bad Request
Content-Length: <span class="hljs-number">22</span>
Content-Type: text/plain; charset=UTF-<span class="hljs-number">8</span>
Connection: keep-alive
The username <span class="hljs-keyword">is</span> too short!
</code></pre>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>I hope this simple article was helpful and shows you how to develop a working backend for your mobile application with the same principles and tools as in your android app.</p>
<p>If you want to find more, you definitely should check the <a target="_blank" href="https://ktor.io/docs">KTOR documentation</a> which is full of good examples.</p>
<p>Honestly, it was fun writing something different than the mobile app — you should try it!</p>
<p><em>This post was originally published on</em> <a target="_blank" href="https://speednet.pl/blog/ktor-as-a-backend-3/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=ktor3"><em>Speednet blog</em></a> <em>on 10.11.2022</em></p>
]]></content:encoded></item><item><title><![CDATA[KTOR as a backend - part 1]]></title><description><![CDATA[Introduction to building a backend with KTOR, covering project setup, routing, and basic API endpoints for a game shop application]]></description><link>https://michalkonkel.dev/ktor-as-a-backend-part-1</link><guid isPermaLink="true">https://michalkonkel.dev/ktor-as-a-backend-part-1</guid><category><![CDATA[ktor]]></category><category><![CDATA[backend]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[ktor client]]></category><category><![CDATA[backend developments]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Mon, 14 Nov 2022 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720758187718/57307366-b0a0-42b2-9341-471cfee621fd.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This article is the first part of the three-part series that will smoothly introduce</em> <strong><em>KTOR as a backend</em></strong> <em>that can be built in a blink of an eye.</em></p>
<p>I am sure that if you are an Android Developer with some good background, experience in Kotlin, and some fun with <a target="_blank" href="https://kotlinlang.org/docs/multiplatform.html">Kotlin Multiplatform</a> — you don’t think of yourself as a full stack dev — but you should! All the good practices, well-known libraries, and functional ways of programming can be transferred from Android to a different domain and still make things happen.</p>
<p>In this article, I would like to introduce you to <a target="_blank" href="https://ktor.io/">Ktor</a> as a backend for your application. It is a brilliant and ready-to-go solution that can be built in a blink of an eye. The Ktor itself provides the best definition:  </p>
<blockquote>
<p><em>Ktor is a framework to easily build connected applications — web applications, HTTP services, mobile and browser applications. Modern connected applications need to be asynchronous to provide the best experience to users, and Kotlin coroutines provide excellent facilities to do it easily and straightforwardly.</em></p>
</blockquote>
<p>The project is available on <a target="_blank" href="https://github.com/mkonkel/KtorBackend">GitHub</a> repo.</p>
<hr />
<h1 id="heading-lets-create-a-project"><strong>Let’s create a project</strong></h1>
<p>For example, we will create a simple Game Shop where users can view available games and place an order.</p>
<p>With <a target="_blank" href="https://www.jetbrains.com/idea/">IntelliJ</a> is very easy to bootstrap your project as the IDE got a dedicated plugin to create the Ktor project.</p>
<p>Open IntelliJ and follow the steps:</p>
<ul>
<li><p>Run the project Wizard <code>New Project</code> or <code>File | New | project</code></p>
</li>
<li><p>Choose <strong>Ktor</strong> from the <strong>generators</strong> section</p>
</li>
<li><p>Fill the project details with desired data</p>
</li>
</ul>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*4Mh80e7gf6l0Pv0Nq9aflg.png" alt="IntelliJ, New Project tab" /></p>
<p>On the next page, we can install some plugins that will be included in the project.<br />In the beginning, we need only one <a target="_blank" href="https://ktor.io/docs/routing-in-ktor.html"><strong>Routing</strong></a>, which is the core Ktor plugin responsible for handling requests and responses in the server application.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*cJAHhz3lhnzA3Xdubz0J3w.png" alt /></p>
<p>Click <strong>Create</strong> and wait for the build to end. You can see the project structure and an <code>Application.kt</code> on the left pane. Inside the file, we’ve got the <strong>embeddedServer</strong> function responsible for project configuration and running the application.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
   embeddedServer(Netty, port = <span class="hljs-number">8080</span>, host = <span class="hljs-string">"0.0.0.0"</span>) {
       configureRouting()
   }.start(wait = <span class="hljs-literal">true</span>)
}
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*qc98HF1x2tcFOfWTyS0yHw.png" alt /></p>
<p>The <strong>configureRouting</strong> extension function contains the routing information.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureRouting</span><span class="hljs-params">()</span></span> {
   routing {
       <span class="hljs-keyword">get</span>(<span class="hljs-string">"/"</span>) {
           call.respondText(<span class="hljs-string">"Hello World!"</span>)
       }
   }
}
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:628/1*HbnRzPWOTzYxyxiLYhLQAw.png" alt /></p>
<p>The routing with address “/” will lead us to the blank page with the “Hello World”. To check if this works, we need to run our application. Go to <code>Application.kt</code> and click the <strong>Run Application</strong> option from the context menu.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*XaChsM4yWz9dsc3cPT-nGQ.png" alt /></p>
<p>After the successful execution, we can see in the terminal window that the app is started on <code>http://localhost</code>, with port <code>8080</code>.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*xTER6A4zKw5McH1cK1xbwg.png" alt /></p>
<p>With the working application, we can now go a bit further and create some basic API for our game shop.</p>
<h1 id="heading-creating-routes-games-endpoint"><strong>Creating Routes — games endpoint</strong></h1>
<p>With our project up and running, we should think about some REST API for our Game Shop, to do this, we need to use the <a target="_blank" href="https://ktor.io/docs/routing-in-ktor.html">Routing</a> plugin. The plugin handles all incoming requests, provides endpoints, and serves the response. To do so, we need it in the application.</p>
<p>Let’s go to the <strong>configureRouting</strong> function and create CRUD endpoints for games, we can start with a route for fetching all the games in the shop. To do this, we need to define the handler.</p>
<pre><code class="lang-kotlin">route(<span class="hljs-string">"/games"</span>) {
    <span class="hljs-keyword">get</span> {
        call.respondText(<span class="hljs-string">"Games"</span>)
    }
}
</code></pre>
<p>When we run our application and try to invite the <code>GET</code> request on the address <code>0.0.0.0:8080/games</code><em>,</em> we should receive the following response. IntelliJ gives us a great tool for such a call — HTTP Request.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*qKCAlZNdjwIxWIqI5cM_gQ.png" alt /></p>
<pre><code class="lang-kotlin">### GET - <span class="hljs-keyword">get</span> Games List
GET http:<span class="hljs-comment">//0.0.0.0:8080/games</span>
Content-Type: application/json
</code></pre>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*ccySGbbNa9RV5KsK_hMCXQ.png" alt /></p>
<p>That concludes our first endpoint with functional requests and responses. However, this implementation is somewhat simplistic and could be improved. We should enhance our codebase to align with standards expected in a professional application.</p>
<p>We can organize our code, add some modules, classes, and a bit of abstraction. To start, we can divide our code into well-structured packages.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*WWGTuFnuZbYkjylUQVKDag.png" alt /></p>
<p>The <strong>data</strong> package will hold the request-response objects. With the usage of the <a target="_blank" href="https://kotlinlang.org/docs/serialization.html"><strong>kotlinx.serialization</strong></a>, we can create a data class that will be used in our endpoint</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Game</span></span>(
   <span class="hljs-keyword">val</span> id: String,
   <span class="hljs-keyword">val</span> name: String,
   <span class="hljs-keyword">val</span> price: <span class="hljs-built_in">Float</span>,
   <span class="hljs-keyword">val</span> genre: String
)
</code></pre>
<p>Then in the <strong>domain</strong> package, we can create a <strong>GamesRepository</strong> interface and its implementation, for now, it will hold data in a local mutable list and simulate storage.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">GamesRepository</span> </span>{
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getGames</span><span class="hljs-params">()</span></span>: List&lt;Game&gt;
}

<span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GamesRepositoryImpl</span> : <span class="hljs-type">GamesRepository {</span></span>
   <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> games: MutableList&lt;Game&gt; = mutableListOf()

   <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getGames</span><span class="hljs-params">()</span></span>: List&lt;Game&gt; {
       <span class="hljs-keyword">return</span> games
   }
}
</code></pre>
<p>To be able to access the repository from any point in the app, we can create an object that will be providing the repo.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> GamesFeature {
   <span class="hljs-keyword">val</span> repository: GamesRepository = GamesRepositoryImpl()
}
</code></pre>
<p>With all pieces configured, we can start working with the presentation layer, which in our case, will not include any UI but only the Routing. We can create an extension function with games-specific routing.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">gamesRouting</span><span class="hljs-params">()</span></span> {
   route(<span class="hljs-string">"/games"</span>) {
       <span class="hljs-keyword">val</span> gamesRepo = GamesFeature.repository


       <span class="hljs-keyword">get</span> {
           <span class="hljs-keyword">val</span> games = gamesRepo.getGames()
           call.respondText(text = games.toString(), status = HttpStatusCode.OK)
       }
</code></pre>
<p>If we rerun our test request, we will see that the app returns an empty array — which is correct since we didn’t add any games yet! To do so, we need to define a request data class, a repository method for adding the new game to the collection, and a new endpoint that will allow us to <strong>POST</strong> a game.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GameRequest</span></span>(
   <span class="hljs-keyword">val</span> name: String,
   <span class="hljs-keyword">val</span> price: String,
   <span class="hljs-keyword">val</span> genre: String
)

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">GamesRepository</span> </span>{
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">addGame</span><span class="hljs-params">(game: <span class="hljs-type">GameRequest</span>)</span></span> : Game
}

<span class="hljs-keyword">internal</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GamesRepositoryImpl</span> : <span class="hljs-type">GamesRepository {</span></span>
   <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">addGame</span><span class="hljs-params">(game: <span class="hljs-type">GameRequest</span>)</span></span>: Game {
      <span class="hljs-keyword">return</span> Game(
          id = UUID.randomUUID().toString(),
          name = game.name,
          price = game.price.toFloat(),
          genre = game.genre
       )
       .also { games.add(it) }
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">gamesRouting</span><span class="hljs-params">()</span></span> {
   route(<span class="hljs-string">"/games"</span>) {
         post {
             <span class="hljs-keyword">val</span> gameRequest = call.receive&lt;GameRequest&gt;()
             <span class="hljs-keyword">val</span> game = gamesRepo.addGame(gameRequest)
             call.respond(
                   status = HttpStatusCode.Created,
                   message = game
             )
          }
}
</code></pre>
<p>There is one new thing in the code above <code>call.receive&lt;GameRequest&gt;()</code> this will allow us to retrieve the body of a POST request, which can now be passed further to a repository.</p>
<p>We can easily handle the response using a Ktor plugin <strong>ContentNegotiation</strong> and <a target="_blank" href="https://ktor.io/docs/serialization.html"><strong>Serialization</strong></a>. To do so, we can create another extension function and use it in our <code>Application.kt</code> file.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
   embeddedServer(Netty, port = <span class="hljs-number">8080</span>, host = <span class="hljs-string">"0.0.0.0"</span>) {
       …
       configureSerialization()
   }.start(wait = <span class="hljs-literal">true</span>)
}
</code></pre>
<p>We can also improve the <strong>GET</strong> games endpoint to handle fetching the game list more smoothly.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">get</span> {
   <span class="hljs-keyword">val</span> games = gamesRepo.getGames()

   <span class="hljs-keyword">if</span> (games.isNotEmpty()) {
       call.respond(games)
   } <span class="hljs-keyword">else</span> {
       call.respondText(text = <span class="hljs-string">"There are no games in our shop yet..."</span>, status = HttpStatusCode.OK)
   }
}
</code></pre>
<p>With all of that, we can try to make some requests and see if everything works fine.</p>
<pre><code class="lang-kotlin">### POST - Add game
POST http:<span class="hljs-comment">//0.0.0.0:8080/games</span>
Content-Type: application/json
{
 <span class="hljs-string">"name"</span>: <span class="hljs-string">"Doom 2"</span>,
 <span class="hljs-string">"price"</span>: <span class="hljs-string">"10.00"</span>,
 <span class="hljs-string">"genre"</span>: <span class="hljs-string">"FPS"</span>
}

### GET - <span class="hljs-keyword">get</span> Games List
GET http:<span class="hljs-comment">//0.0.0.0:8080/games</span>
Content-Type: application/json
</code></pre>
<p>Running those two requests should create a game and return the list of games. The complete example can be found on <a target="_blank" href="https://github.com/mkonkel/KtorBackend/blob/master/src/main/kotlin/pl/mkonkel/features/games/presentation/GamesRoutes.kt">GitHub</a>.</p>
<p>The routing plugin supports all the verbs, such as <strong>PUT</strong>, <strong>DETELE, HEAD</strong> and others. It can also provide a way to specify path parameters <code>/games/{id},</code> which can be obtained with a <code>call.parameters[“id”]</code> function or query parameters <strong>/</strong><code>games?genere=FPS</code> available with <code>call.request.queryParameters[“genre”]</code> so we can easily model our games endpoint</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">get</span>(<span class="hljs-string">"{id?}"</span>) {
   <span class="hljs-keyword">val</span> id = call.parameters[<span class="hljs-string">"id"</span>] ?: <span class="hljs-keyword">return</span><span class="hljs-symbol">@get</span> call.respondText(
       text = <span class="hljs-string">"Id is required"</span>,
       status = HttpStatusCode.BadRequest
   )

   <span class="hljs-keyword">val</span> game = gamesRepo.getGame(id) ?: <span class="hljs-keyword">return</span><span class="hljs-symbol">@get</span> call.respondText(
       text = <span class="hljs-string">"Game with <span class="hljs-variable">$id</span> does not exist"</span>,
       status = HttpStatusCode.NotFound
   )

   call.respond(game)
}
</code></pre>
<p>As you can see, with the <code>respondText</code> and <code>respond</code> methods, we are providing the response to the client, thanks to the <strong>kotlinx.serialziation</strong> and <strong>content negotiation</strong> plugins, the user will receive the data in JSON format. We can also provide response codes such as 200, 204, 400, 500, etc.</p>
<h1 id="heading-type-safe-routing-orders-endpoint"><strong>Type safe routing — orders endpoint</strong></h1>
<p>With some games in the shop, it would be nice to allow users to buy a game, to do so they need to place an order. From the code point of view, the design will be the same — request, response classes, repository, and routing. But to be honest, fetching parameters with <code>call.parameters[“id”]</code> can be tricky and requires some work — we can be smarter and use <strong>the Resources</strong> plugin that provides type-safe routing with the support of query parameters and path parameters.</p>
<p>First, we need to add the dependency into our gradle file and install the plugin in our application.</p>
<pre><code class="lang-kotlin">implementation(<span class="hljs-string">"io.ktor:ktor-server-resources:<span class="hljs-variable">$ktor_version</span>"</span>)

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
   embeddedServer(Netty, port = <span class="hljs-number">8080</span>, host = <span class="hljs-string">"0.0.0.0"</span>) {
       install(Routing)
       install(Resources)
</code></pre>
<p>Then with the given structure, let’s inspect the <strong>OrdersResources</strong>.</p>
<p>Orders allow us to structure the code in a more convenient and easily manageable way, all resources needed to be annotated with <code>@Serialziation</code> and <code>@Resources</code>. Resources support nested classes that can indicate that our paths belong to the exact origin. The nested class needs to include its parent in the constructor parameter.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Serializable</span>
<span class="hljs-meta">@Resource(<span class="hljs-meta-string">"/orders"</span>)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrdersResources</span></span>(<span class="hljs-keyword">val</span> genre: String? = <span class="hljs-literal">null</span>) {

   <span class="hljs-meta">@Serializable</span>
   <span class="hljs-meta">@Resource(<span class="hljs-meta-string">"{id}"</span>)</span>
   <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Id</span></span>(<span class="hljs-keyword">val</span> parent: OrdersResources = OrdersResources(), <span class="hljs-keyword">val</span> id: String) {
       <span class="hljs-meta">@Serializable</span>
       <span class="hljs-meta">@Resource(<span class="hljs-meta-string">"edit"</span>)</span>
       <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Edit</span></span>(<span class="hljs-keyword">val</span> parent: Id, <span class="hljs-keyword">val</span> name: String)

       <span class="hljs-meta">@Serializable</span>
       <span class="hljs-meta">@Resource(<span class="hljs-meta-string">"address"</span>)</span>
       <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Address</span></span>(<span class="hljs-keyword">val</span> parent: Id)
   }
}
</code></pre>
<p>What we’ve done here is defining the endpoints for the orders feature, going from top to bottom, we have:</p>
<ul>
<li><p><code>/orders</code> <em>path for fetching the list of otters with optional query parameter price that can be used for filtering.</em></p>
</li>
<li><p><code>/orders</code> <em>path for creating an order</em></p>
</li>
<li><p><code>/orders/{id}</code> <em>path for fetching the details of one order</em></p>
</li>
<li><p><code>/orders/(id}</code> path for deleting the order</p>
</li>
<li><p><code>/orders/(id}</code> <em>path for editing the order</em></p>
</li>
<li><p><code>/orders/{id}/address</code> <em>path for fetching the delivery address</em></p>
</li>
</ul>
<p>With such defined resources, we can go to our routing class and use the created paths — we need to visit the <code>OrdersRoute.kt</code><strong>.</strong> In the beginning, we should start with something simple — a list of all games.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">get</span>&lt;OrdersResources&gt; {
   <span class="hljs-keyword">val</span> orders = repo.getOrders()
   call.respond(orders)
}
</code></pre>
<p>That’s all, instead of writing the path, we are using the resources class.</p>
<p>Now let's implement fetching the order by its id.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">get</span>&lt;OrdersResources.Id&gt; { request -&gt;
   <span class="hljs-keyword">val</span> order = repo.getOrder(request.id)

   order?.let { call.respond(it) } ?: call.respondText(
       status = HttpStatusCode.BadRequest,
       text = <span class="hljs-string">"No such order! OrderId: <span class="hljs-subst">${request.id}</span>"</span>
   )
}
</code></pre>
<p>In lambda, we are able to access the <strong>request</strong> with the usage of <strong>resources</strong> the request handler is aware of the shape processing call and can easily access the <strong>id</strong> parameter and perfectly knows that its type is a String. There is nothing more left than asking the repo for an order with a given id and providing proper responses <strong>200</strong> with data or <strong>400</strong> if the order does not exist.</p>
<pre><code class="lang-kotlin">post&lt;OrdersResources&gt; {
   <span class="hljs-keyword">val</span> orderRequest = call.receive&lt;OrderRequest&gt;()
   <span class="hljs-keyword">val</span> newOrder = repo.addOrder(orderRequest)
   call.respond(newOrder)
}

delete&lt;OrdersResources.Id&gt; { request -&gt;
   <span class="hljs-keyword">try</span> {
       repo.delete(request.id)
       call.respond(
           status = HttpStatusCode.NoContent,
           message = <span class="hljs-string">"Order deleted"</span>
       )
   } <span class="hljs-keyword">catch</span> (e: Exception) {
       call.respondText(
           status = HttpStatusCode.BadRequest,
           text = <span class="hljs-string">"No such order! OrderId: <span class="hljs-subst">${request.id}</span>"</span>
       )
   }
}
</code></pre>
<p>Creating and deleting the orders works the same way, the interesting part is when we are trying to obtain only the delivery address.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">get</span>&lt;OrdersResources.Id.Address&gt; { request -&gt;
   <span class="hljs-keyword">val</span> address = repo.getOrder(request.parent.id)?.address
   address?.let { call.respond(it) } ?: call.respondText(<span class="hljs-string">"No such order! OrderId: <span class="hljs-subst">${request.parent.id}</span>"</span>)
}
</code></pre>
<p>If we want to obtain the <strong>id</strong> from the path, we need to call the <strong>parent</strong> nested class for it, and after that, we can fetch the <strong>address</strong> from the rest of the request path.</p>
<p>Using the query param is also really simple, let’s filter out orders based on their price.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">get</span>&lt;OrdersResources&gt; { request -&gt;
   <span class="hljs-keyword">val</span> price = request.price ?: <span class="hljs-number">0</span>
   <span class="hljs-keyword">val</span> orders = repo.getOrders()
       .filter { it.price &gt; price }

   call.respond(orders)
}
</code></pre>
<p>Now we can write some HTTP Requests and check if our code is working as expected. Running requests one by one, you should be able to go through the whole process.</p>
<pre><code class="lang-http">### POST - add game
<span class="hljs-attribute">POST http://0.0.0.0:8080/games
Content-Type</span>: application/json

<span class="dart">{
 <span class="hljs-string">"name"</span>: <span class="hljs-string">"Doom 2"</span>,
 <span class="hljs-string">"price"</span>: <span class="hljs-string">"10.00"</span>,
 <span class="hljs-string">"genre"</span>: <span class="hljs-string">"FPS"</span>
}

&gt; {%
   client.global.<span class="hljs-keyword">set</span>(<span class="hljs-string">"game_id"</span>, response.body.id);
%}

### POST - create an order
POST http:<span class="hljs-comment">//0.0.0.0:8080/orders</span>
Content-<span class="hljs-built_in">Type</span>: application/json

{
 <span class="hljs-string">"games"</span> : [{{game_id}}],
 <span class="hljs-string">"address"</span>: <span class="hljs-string">"Street 12, City 11-222"</span>
}

### GET - <span class="hljs-keyword">get</span> all orders <span class="hljs-keyword">with</span> price greater than <span class="hljs-number">20</span>
GET http:<span class="hljs-comment">//0.0.0.0:8080/orders?price=20</span>
Content-<span class="hljs-built_in">Type</span>: application/json

### GET - <span class="hljs-keyword">get</span> all orders
GET http:<span class="hljs-comment">//0.0.0.0:8080/orders</span>
Content-<span class="hljs-built_in">Type</span>: application/json

&gt; {%
   client.global.<span class="hljs-keyword">set</span>(<span class="hljs-string">"order_id"</span>, response.body[<span class="hljs-number">0</span>].id);
%}

### GET - <span class="hljs-keyword">get</span> single order by ID
GET http:<span class="hljs-comment">//0.0.0.0:8080/orders/{{order_id}}</span>

Content-<span class="hljs-built_in">Type</span>: application/json

### GET - <span class="hljs-keyword">get</span> order address
GET http:<span class="hljs-comment">//0.0.0.0:8080/orders/{{order_id}}/address</span>
Content-<span class="hljs-built_in">Type</span>: application/json

### DELETE - deleto order
DELETE http:<span class="hljs-comment">//0.0.0.0:8080/orders/{{order_id}}</span>
Content-<span class="hljs-built_in">Type</span>: application/json</span>
</code></pre>
<p>We’ve reached the end of the first part of the article. I hope you’ve enjoyed it and you can’t wait for more.</p>
<p><em>This post was originally published on</em> <a target="_blank" href="https://speednet.pl/blog/ktor-as-a-backend/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=ktor"><em>Speednet blog</em></a> <em>on 10.11.2022</em></p>
]]></content:encoded></item><item><title><![CDATA[KTOR as a backend - part 2]]></title><description><![CDATA[Enhance your KTOR backend with Dependency Injection and Database integration for a modular, resilient game shop architecture]]></description><link>https://michalkonkel.dev/ktor-as-a-backend-part-2</link><guid isPermaLink="true">https://michalkonkel.dev/ktor-as-a-backend-part-2</guid><category><![CDATA[ktor]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Databases]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[koin]]></category><category><![CDATA[h2]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Mon, 14 Nov 2022 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720765610285/b3273286-b5c1-47d1-b051-ca405543286f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post, we will take significant steps to enhance our game shop backend by incorporating Dependency Injection and integrating a robust Database system. First, we will explore the concept of Dependency Injection, understanding how it can help us manage dependencies more effectively and promote a cleaner, more modular codebase. We will then move on to setting up a Database, we will cover the entire process, from initial setup and configuration to implementing CRUD operations. By the end of this post, you will have a comprehensive understanding of how to improve the architecture and functionality of your game shop backend.</p>
<h1 id="heading-dependency-injection-users-endpoint"><strong>Dependency Injection — users endpoint</strong></h1>
<p>With the possibility of adding a game and creating an order, it would be nice to assign such an order with a user — we’ve got some working endpoints, and adding a new one is pretty straightforward, but we can do a bit more and improve our codebase by introducing the dependency injection library instead of using an object with repository — here comes the <a target="_blank" href="https://insert-koin.io/">KOIN</a> a well know DI framework straight from the android world.</p>
<p>I will not elaborate on how <strong>KOIN</strong> works and dive into the details, everything can be found in the documentation — here, we are just adding di to the project.</p>
<p>In the beginning, we need to add proper dependencies and install the plugin.</p>
<pre><code class="lang-kotlin">implementation(<span class="hljs-string">"io.insert-koin:koin-ktor:<span class="hljs-variable">$koin_version</span>"</span>)
implementation(<span class="hljs-string">"io.insert-koin:koin-logger-slf4j:<span class="hljs-variable">$koin_version</span>"</span>)g
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureDI</span><span class="hljs-params">()</span></span> {
   install(Koin) {
       slf4jLogger()
   }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
   embeddedServer(Netty, port = <span class="hljs-number">8080</span>, host = <span class="hljs-string">"0.0.0.0"</span>) {
       configureDI()
       …
}
</code></pre>
<p>From now on, we can use all the good stuff that KOIN is capable of. Let’s proceed with some standard classes that we did in previous examples; <strong>User</strong>, <strong>UserRequest</strong>, <strong>UsersRepository</strong>, and <strong>UsersRoutes</strong>, without going into the details, the repo is still holding the data in a mutable list, but now it will be injected into the routes.</p>
<p>To do so, we need to declare the <strong>module</strong>, which in our case will be <strong>appModule</strong>, in this module, we will create the singleton for our repository.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> appModule = module {
   single&lt;UsersRepository&gt; { UsersRepositoryImpl() }
}
</code></pre>
<p>Then this module needs to be added to the Koin container, after that, we are ready to go and can inject our repository wherever we want.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureDI</span><span class="hljs-params">()</span></span> {
   install(Koin) {
       slf4jLogger()
       modules(appModule)
   }
}
</code></pre>
<p>A good place to start is the <strong>UsersRoutes</strong>, where we can create or get a list of our users. With this simple config, we are good to go.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> Route.<span class="hljs-title">usersRouting</span><span class="hljs-params">()</span></span> {
   <span class="hljs-keyword">val</span> repo <span class="hljs-keyword">by</span> inject&lt;UsersRepository&gt;()

   route(<span class="hljs-string">"/users"</span>) {
       <span class="hljs-keyword">get</span> {
           <span class="hljs-keyword">val</span> users = repo.getUsers()

           call.respond(
        status = HttpStatusCode.OK,
    message = users
    )
    }
}
</code></pre>
<p><strong>Database — users endpoint</strong></p>
<p>For the presentation, it was a simple and quick solution to store data in a mutable list, but the data vanishes with every application restart if we want our data to persist over the server downs and ups, we need to implement a database.</p>
<p>There are a few frameworks that will help us with databases. I will choose the <a target="_blank" href="https://github.com/JetBrains/Exposed"><strong>Exposed</strong></a> delivered by Jetbrains as the ORM framework. It will be connected with <a target="_blank" href="https://github.com/h2database/h2database"><strong>H2 database</strong></a> — which is not a great choice for production but will be enough as an example.</p>
<pre><code class="lang-kotlin">gradle.properties
exposed_version = <span class="hljs-number">0.36</span><span class="hljs-number">.2</span>
h2_version = <span class="hljs-number">1.4</span><span class="hljs-number">.200</span>
</code></pre>
<pre><code class="lang-kotlin">build.gradle.kts
<span class="hljs-keyword">val</span> exposed_version: String <span class="hljs-keyword">by</span> project
<span class="hljs-keyword">val</span> h2_version: String <span class="hljs-keyword">by</span> project

dependencies {
    implementation(<span class="hljs-string">"org.jetbrains.exposed:exposed-core:<span class="hljs-variable">$exposed_version</span>"</span>)
    implementation(<span class="hljs-string">"org.jetbrains.exposed:exposed-dao:<span class="hljs-variable">$exposed_version</span>"</span>)
    implementation(<span class="hljs-string">"org.jetbrains.exposed:exposed-jdbc:<span class="hljs-variable">$exposed_version</span>"</span>)
    implementation(<span class="hljs-string">"com.h2database:h2:<span class="hljs-variable">$h2_version</span>"</span>)
}
</code></pre>
<p>For convenience, let’s put everything related to DB in the <strong>database</strong> package. We need to start with the <strong>users’ table</strong> to do so let’s create a model first.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> Users : UUIDTable() {
   <span class="hljs-keyword">val</span> name = varchar(<span class="hljs-string">"name"</span>, <span class="hljs-number">128</span>)
   <span class="hljs-keyword">val</span> date_created = varchar(<span class="hljs-string">"date_created"</span>, <span class="hljs-number">10</span>)
   <span class="hljs-keyword">val</span> username = varchar(<span class="hljs-string">"username"</span>, <span class="hljs-number">128</span>)
   <span class="hljs-keyword">val</span> password = varchar(<span class="hljs-string">"password"</span>, <span class="hljs-number">128</span>)
}
</code></pre>
<p>In a nutshell, the <strong>UUIDTable</strong> class from Exposed will create a table where the <strong>id</strong> will be the primary key with the auto-generated UUID, all fields of the stored user are <strong>varchar</strong> where the <strong>varchar</strong> function can receive the name of a column, and its max length. For more details about how to create models, you can check the <a target="_blank" href="https://github.com/JetBrains/Exposed/wiki/DAO#overview"><strong>documentation</strong></a>.</p>
<p>After the table is defined, we need to create a <strong>DatabaseFactory</strong> interface, and its implementation will be responsible for establishing the connection with the database.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">DatabaseFactory</span> </span>{
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseFactoryImpl</span> : <span class="hljs-type">DatabaseFactory {</span></span>
   <span class="hljs-keyword">private</span> <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
       <span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> driverClassName = <span class="hljs-string">"org.h2.Driver"</span>
       <span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> jdbcURL = <span class="hljs-string">"jdbc:h2:file:./build/db"</span>
   }


   <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">()</span></span> {
       Database.connect(jdbcURL, driverClassName)
   }
}
</code></pre>
<p>This should be enough for our DB to be available in the project. There is one more thing that we need to do — create the Users table. To do so, we can create a helper method that will be responsible for creating the schemas, let’s go back to <strong>DatabaseFactoryImpl</strong>.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-keyword">object</span> SchemaDefinition {
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createSchema</span><span class="hljs-params">()</span></span> {
       transaction {
           SchemaUtils.create(Users)
       }
   }
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureDatabase</span><span class="hljs-params">()</span></span> {
   …
   SchemaDefinition.createSchema()
}
</code></pre>
<p>The database will be created in the build folder of our project. Then we need to add this factory to our Koin module and use it at the start of our server.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> appModule = module {
   …
   single&lt;DatabaseFactory&gt; { DatabaseFactoryImpl() }
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> Application.<span class="hljs-title">configureDatabase</span><span class="hljs-params">()</span></span> {
   <span class="hljs-keyword">val</span> databaseFactory <span class="hljs-keyword">by</span> inject&lt;DatabaseFactory&gt;()
   databaseFactory.create()
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
   embeddedServer(Netty, port = <span class="hljs-number">8080</span>, host = <span class="hljs-string">"0.0.0.0"</span>) {
       …
       configureDatabase()
   }.start(wait = <span class="hljs-literal">true</span>)
}
</code></pre>
<p>So from now on, users can be stored in the database — but this is only halfway — we need to improve our repository to work with the DB fully. For this, we will create the <strong>UsersDAOFacade</strong> interface with implementation — this pattern will hide the details of DB from the application domain.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UsersDAOFacade</span> </span>{
   <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createUser</span><span class="hljs-params">(userRequest: <span class="hljs-type">UserRequest</span>)</span></span>: User?
   <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsers</span><span class="hljs-params">()</span></span>: List&lt;User&gt;
}
</code></pre>
<p>Instead of using blocking <strong>transactions</strong> in every DB query, we can use the coroutines and handle every query in a single coroutine — this little helper function can do the trick:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-type">&lt;T&gt;</span> <span class="hljs-title">dbQuery</span><span class="hljs-params">(block: <span class="hljs-type">suspend</span> () -&gt; <span class="hljs-type">T</span>)</span></span>: T =
   newSuspendedTransaction(Dispatchers.IO) { block() }
</code></pre>
<p>The implementation of the facade will be very easy. We need to map requests to the database representation and the other way around. Because the definition of a table is a kotlin object, we can access its properties everywhere.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createUser</span><span class="hljs-params">(userRequest: <span class="hljs-type">UserRequest</span>)</span></span> = dbQuery {
   Users.insert {
       it[name] = userRequest.name
       it[username] = userRequest.username
       it[password] = userRequest.password
       it[date_created] = Clock.System.now().toLocalDateTime(TimeZone.UTC).date.toString()
   }
       .resultedValues?.singleOrNull()?.toUser()
}

<span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsers</span><span class="hljs-params">()</span></span>: List&lt;User&gt; = dbQuery {
   Users.selectAll().map { it.toUser() }
}
</code></pre>
<p>For the date handling, we are using <a target="_blank" href="https://github.com/Kotlin/kotlinx-datetime"><strong>kotlinx-datetime</strong></a> the functions are pretty clear, each db request is using our helper function, each request returns the <strong>ResultRow</strong> object that holds the data. The obtained data is then mapped to/from domain objects.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> ResultRow.<span class="hljs-title">toUser</span><span class="hljs-params">()</span></span>: User {
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.let {
       User(
           id = it[Users.id].toString(),
           name = it[Users.name],
           username = it[Users.username]
       )
   }
}
</code></pre>
<p>The last thing to do is to add the DB to the repository, let’s change the mutableList to the proper functions that will use a DB. For the Repository, we will inject the repo with the constructor (which includes a slight change in the koin module)</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UsersRepositoryImpl</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> dao: UsersDAOFacade) : UsersRepository {

   <span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">addUser</span><span class="hljs-params">(userRequest: <span class="hljs-type">UserRequest</span>)</span></span>: User? {
       <span class="hljs-keyword">return</span> dao.createUser(userRequest)
   }

   <span class="hljs-keyword">override</span> <span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsers</span><span class="hljs-params">()</span></span>: List&lt;User&gt; {
       <span class="hljs-keyword">return</span> dao.getUsers()
   }
}

<span class="hljs-keyword">val</span> appModule = module {
   single&lt;UsersRepository&gt; { UsersRepositoryImpl(<span class="hljs-keyword">get</span>()) }
}
</code></pre>
<p>From now on, every added user will be stored in the database and persisted between the server restarts. To start with the fresh <strong>DB</strong>, you can always go to /<em>build</em> <strong>f</strong>older and remove the database. There are some useful tools for handling migrations, for example, <a target="_blank" href="https://www.liquibase.org/"><strong>liquibase</strong></a> (which is not a part of this article).</p>
<p>We’ve reached the end of the second part of the article. I hope you’ve enjoyed it and you can’t wait for more.</p>
<p><em>This post was originally published on</em> <a target="_blank" href="https://speednet.pl/blog/ktor-as-a-backend-2/?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=ktor2"><em>Speednet blog</em></a> <em>on 10.11.2022</em></p>
]]></content:encoded></item><item><title><![CDATA[Room Persistence Library Introduction — part 1]]></title><description><![CDATA[Introduction to configuring and using Room Persistence Library in Android projects. Part 1 of a 3-part series]]></description><link>https://michalkonkel.dev/room-persistence-library-introduction-part-1</link><guid isPermaLink="true">https://michalkonkel.dev/room-persistence-library-introduction-part-1</guid><category><![CDATA[Android]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Databases]]></category><category><![CDATA[room database]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[mobile]]></category><category><![CDATA[Jetpack Compose]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Tue, 16 Oct 2018 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720672214247/634b704d-bbb8-4372-8f4a-6d95debebead.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This article is the first part of the three-part series that will smoothly introduce Room Persistence Library to you. The first part will be focused on configuring the project and explaining the basic structures.</em> All sources can be found in related <a target="_blank" href="https://github.com/mkonkel/RoomBeginners"><strong><em>GitHub</em></strong></a> project.</p>
<h1 id="heading-what-is-room"><strong>What is Room?</strong></h1>
<p>The Room is a persistence library that provides an object-mapping abstraction layer over SQLite to more robust database access while harnessing the full power of SQLite. It comes along with the Architecture components and was presented at Google I/O in 2017. Now it has reached version 2.0 and it is a part of Android Jetpack (on 10.10.2018 the 2.1 alpha 1 version was released). In this article, we will focus on version 1.1.1.</p>
<h1 id="heading-lets-start"><strong>Let’s start!</strong></h1>
<p>At the beginning we need to create an Android Project with the Kotlin support, API 27 (or greater) with “No Activity” option. To use Room we need to add some dependencies to our gradle file.</p>
<pre><code class="lang-plaintext">dependencies {
    def room_version = "1.1.1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    kapt "android.arch.persistence.room:compiler:$room_version"

   ...
}
</code></pre>
<h2 id="heading-basic-elements"><strong>Basic elements</strong></h2>
<p>Room consists of a few basic elements that you should know before starting any work.</p>
<h2 id="heading-entity"><code>@Entity</code></h2>
<p>A class annotated with <code>@Entity</code> will represent our column in the database. Basically, it is just a POJO set of related fields.</p>
<p>By default, Room creates a column for each field that’s defined in the entity. If an entity has fields that you don’t want to persist, you can annotate them using <code>@Ignore</code> annotation.<br />To persist a field, Room must have access to it. You have to make a field public, or at least provide a getter and setter for it.</p>
<p>The tricky part with <code>@Ignore</code> and Kotlin “behind the scenes” generation of constructors for nullable fields. In that particular case, Kotlin will generate every possible constructor for class with nullable values — this will cause an error — because Room needs an empty constructor. One way is to override constructors as described in the kotlinsdocumentation. The Second one (the easiest one) is to set default values for the fields.</p>
<h2 id="heading-primarykey"><code>@PrimaryKey</code></h2>
<p>Each entity must define at least one field as a primary key. Even when there is only one field, you still need to annotate the field with the <code>@PrimaryKey</code> annotation. In addition, if you want Room to assign automatic IDs to entities, you should set the <code>@PrimaryKeyautoGenerate</code> property to true. You can also provide a composite primary key, just use the <strong><em>primaryKeys</em></strong> property of the <code>@Entity.</code></p>
<p>By default, Room uses the class name as the database table name. If you want the table to have a different name, set the <strong><em>tableName</em></strong> property of the <code>@Entity</code> annotation. Similarly to the <strong><em>tableName</em></strong> property, Room uses the field names as the column names in the database. If you want a column to have a different name, add the <code>@ColumnInfo</code> annotation to a field.</p>
<p>Let’s write some code!</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity(tableName = <span class="hljs-meta-string">"users"</span>)</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>(
        <span class="hljs-meta">@PrimaryKey(autoGenerate = true)</span>
        <span class="hljs-keyword">var</span> id: <span class="hljs-built_in">Long</span>,

        <span class="hljs-keyword">var</span> firstName: String,

        <span class="hljs-keyword">var</span> lastName: String,

        <span class="hljs-keyword">var</span> fullName: String,

        <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"email"</span>)</span>
        <span class="hljs-keyword">var</span> emailAddress: String,

        <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"phone"</span>)</span>
        <span class="hljs-keyword">var</span> phoneNumber: String,

        <span class="hljs-keyword">var</span> picture: String
)
</code></pre>
<p>What we’ve got here is a simple user entity whose name will be users, primary key will be autogenerated long. The code above will generate a corresponding table in the database.</p>
<h2 id="heading-dao"><code>@Dao</code></h2>
<p>To access your app’s data using the Room persistence library, you should work with data access objects or DAOs.<br />This set of DAO objects forms the main component of Room, as each DAO includes methods that offer abstract access to your app’s database.<br />Basically, this is the point where you will be communicating with the database — here you will be defining your data interactions, mapping SQL queries to functions and more.</p>
<p>It is recommended to have multiple Dao classes in your codebase depending on the tables they touch. Room creates each DAO implementation at compile time.</p>
<p>DAO consists of 4 major methods <code>@Insert, @Update, @Delete</code> and <code>@Query</code></p>
<h2 id="heading-insert"><code>@Insert</code></h2>
<p>The implementation of the method will insert its parameters into the database.<br />If the <code>@Insert</code> method receives only one parameter, it can return a long, which is the new <strong><em>row_id</em></strong> for the inserted item. If the parameter is an array or a collection, it should return long[] or List&lt;Long&gt; instead.<br /><code>@Insert</code> contains the <strong><em>onConflict</em></strong> property which determines the SQLite conflict resolving strategy when inserting data.</p>
<h2 id="heading-update"><code>@Update</code></h2>
<p>The implementation of the method will update its parameters in the database if they already exist (checked by primary keys). If they don’t already exist, this option will not change the database.</p>
<h2 id="heading-delete"><code>@Delete</code></h2>
<p>The implementation of the method will delete its parameters from the database. It uses the primary keys to find the entities to delete.</p>
<h2 id="heading-query"><code>@Query</code></h2>
<p>The main annotation used in DAO classes allows you to perform read/write operations on a database. The query is verified at compile time by Room to ensure that it compiles fine against the database.</p>
<p>Let’s write some code!</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Dao</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserDao</span> </span>{
    <span class="hljs-meta">@Insert(onConflict = OnConflictStrategy.REPLACE)</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insertUser</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span>

    <span class="hljs-meta">@Insert</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insertUsers</span><span class="hljs-params">(users: <span class="hljs-type">List</span>&amp;<span class="hljs-type">lt</span>;<span class="hljs-type">User</span>&amp;<span class="hljs-type">gt</span>;)</span></span>

    <span class="hljs-meta">@Update</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">updateUser</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span>

    <span class="hljs-meta">@Update</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">updateUsers</span><span class="hljs-params">(<span class="hljs-keyword">vararg</span> users: <span class="hljs-type">User</span>)</span></span>

    <span class="hljs-meta">@Delete</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(user: <span class="hljs-type">User</span>)</span></span>

    <span class="hljs-meta">@Delete</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">deleteUsers</span><span class="hljs-params">(users: <span class="hljs-type">List</span>&amp;<span class="hljs-type">lt</span>;<span class="hljs-type">User</span>&amp;<span class="hljs-type">gt</span>;)</span></span>

    <span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM users"</span>)</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">users</span><span class="hljs-params">()</span></span>: List&amp;lt;User&amp;gt;
}
</code></pre>
<p>As you can see we have some basic methods that allow us to insert, update or delete a single user or a list of users. The methods mentioned above use the primary key to determine which row should be affected.</p>
<p>You can also pass parameters into queries to perform filtering operations, such as only displaying users with a certain name.</p>
<p>Room only supports named bind parameter to avoid any confusion between the method parameters and the query bind parameters.<br />Room will automatically bind the parameters of the method into the bind arguments. This is done by matching the name of the parameters to the name of the bind arguments.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM users WHERE firstName = :userName"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">usersWithName</span><span class="hljs-params">(userName: <span class="hljs-type">String</span>)</span></span>: List&amp;lt;User
</code></pre>
<p>We will focus on this a little bit more in the second part of the article series.</p>
<h1 id="heading-database"><code>@Database</code></h1>
<p>Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data. A class annotated with <code>@Database</code> should be an abstract class and extend <strong>RoomDatabase</strong>. You can receive an implementation of the class via <strong><em>Room.databaseBuilder</em></strong>.</p>
<p><strong>RoomDatabase</strong> provides direct access to the underlying database implementation but you should prefer using Dao classes.</p>
<p>Database class should consist at least of:</p>
<ul>
<li><p>List of entities</p>
</li>
<li><p>DB version</p>
</li>
<li><p>Abstract methods returning DAO’s</p>
</li>
<li><p>Database builder method.</p>
</li>
</ul>
<p>Let’s code to see this in action!</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Database(
        entities = [User::class],
        version = AppDatabase.DB_VERSION
)</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppDatabase</span> : <span class="hljs-type">RoomDatabase</span></span>() {

    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">userDao</span><span class="hljs-params">()</span></span>: UserDao

    <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> DB_VERSION = <span class="hljs-number">1</span>
        <span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> DB_NAME = <span class="hljs-string">"application.db"</span>

        <span class="hljs-meta">@Volatile</span>
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> INSTANCE: AppDatabase? = <span class="hljs-literal">null</span>

        <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getInstance</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span>: AppDatabase =
                INSTANCE ?: synchronized(<span class="hljs-keyword">this</span>) {
                    INSTANCE ?: buildDatabase(context)
                }

        <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">buildDatabase</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span> =
                Room.databaseBuilder(context.applicationContext, AppDatabase::<span class="hljs-keyword">class</span>.java, DB_NAME)
                        .build()
    }
}
</code></pre>
<p>From the beginning:<br />Annotation <code>@Database</code> requires two properties:</p>
<ul>
<li><p>List of entities — the tables in our DB (classes)</p>
</li>
<li><p>DB version</p>
</li>
</ul>
<p>At the top of the class, we should declare all DAO’s as the abstract functions — it’s just a convention.<br />Then, we should always use the singleton pattern to obtain the database object, because the creation of the DB connection is quite expensive.<br />The code above will create room database when anything asks for its instance.</p>
<p>We are also using:</p>
<ul>
<li><p><code>@Volatile</code> — that has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.</p>
</li>
<li><p><code>synchronized(this)</code> — in the simplest words, when you have two threads that are reading and writing to the same ‘resource’ you need to ensure that these threads access the variable in an atomic way. Without it, the thread 1 may not see the change thread 2 made to a variable.</p>
</li>
</ul>
<p>Furthermore, it’s also quite handy to get some Injector class that will provide necessary objects that we will later use in our Activity.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> Injector {
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">provideUserDao</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span>: UserDao {
        <span class="hljs-keyword">return</span> AppDatabase.getInstance(context).userDao()
    }
}
</code></pre>
<p>Another thing we should take care of is <strong>pre-populating</strong> our database in some data set. With the traditional approach the data will probably come from some web API — for this short tutorial, we will use prepared data.</p>
<p>For this task, we will add the <strong>onCreate</strong> callback to the <strong>databaseBuilder</strong>. We should keep in mind that any operation related with the DB cannot be performed on the <strong>mainThread</strong> — because Room will throw an exception — so kotlin coroutine sounds like a good plan for this task.</p>
<p>We will need to add some dependencies to our app gradle.</p>
<pre><code class="lang-plaintext">kotlin {
    experimental {
        coroutines "enable"
    }
}
…
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.26.1'
</code></pre>
<p>Then we also need to add some code to the database builder.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">buildDatabase</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span> =
        Room.databaseBuilder(context.applicationContext, AppDatabase::<span class="hljs-keyword">class</span>.java, DB_NAME)
                .addCallback(dbCreateCallback(context))
                .build()

<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">dbCreateCallback</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span> = <span class="hljs-keyword">object</span> : Callback() {
     <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(db: <span class="hljs-type">SupportSQLiteDatabase</span>)</span></span> {
         <span class="hljs-keyword">super</span>.onCreate(db)
         GlobalScope.launch {
            getInstance(context).userDao()
                    .insertUsers(PrepopulateData.users)
        }
     }
}
</code></pre>
<p>Our prefilled data can look like that:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> PrepopulateData {
    <span class="hljs-keyword">val</span> users = listOf(
            User(
                    id = <span class="hljs-literal">null</span>,
                    firstName = <span class="hljs-string">"John"</span>,
                    lastName = <span class="hljs-string">"Doe"</span>,
                    fullName = <span class="hljs-string">"John Doe"</span>,
                    emailAddress = <span class="hljs-string">"jdoe@mail.com"</span>,
                    phoneNumber = <span class="hljs-string">"001333444555"</span>,
                    picture = <span class="hljs-string">"/pictures/jdoe/avatar/s34trag_732_jkdal.png"</span>
            ),
            User(
                    id = <span class="hljs-literal">null</span>,
                    firstName = <span class="hljs-string">"Mark"</span>,
                    lastName = <span class="hljs-string">"Smith"</span>,
                    fullName = <span class="hljs-string">"Mark Smith"</span>,
                    emailAddress = <span class="hljs-string">"mastermike@mail.com"</span>,
                    phoneNumber = <span class="hljs-string">"001666999888"</span>,
                    picture = <span class="hljs-string">"/pictures/msmith/avatar/123454647_gfas.png"</span>
            )
    )
}
</code></pre>
<p>The given changes will create two new users when <strong>DB</strong> is first created, this will allow us to pre-populate <strong>DB</strong> when it’s first created. Now there is nothing more left for us, let’s finally check if everything works.</p>
<p>We can add some simple activity to validate the code.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestActivity</span> : <span class="hljs-type">AppCompatActivity</span></span>() {

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)

        <span class="hljs-keyword">val</span> userDao = Injector.provideUserDao(<span class="hljs-keyword">this</span>)

        GlobalScope.launch {
            <span class="hljs-keyword">val</span> users = userDao.users()

            users.forEach {
                Log.d(<span class="hljs-string">"User"</span>, “$it<span class="hljs-string">")
            }
        }
    }
}</span>
</code></pre>
<p>Now if you run the application and everything went OK and the is showing a blank screen you should see a log message similar to this</p>
<pre><code class="lang-kotlin">User(id=<span class="hljs-number">1</span>, firstName=John, lastName=Doe, fullName=John Doe, emailAddress=<span class="hljs-symbol">jdoe@</span>mail.com, phoneNumber=<span class="hljs-number">001333444555</span>, picture=/pictures/jdoe/avatar/s34trag_732_jkdal.png)
User(id=<span class="hljs-number">2</span>, firstName=Mark, lastName=Smith, fullName=Mark Smith, emailAddress=<span class="hljs-symbol">mastermike@</span>mail.com, phoneNumber=<span class="hljs-number">001666999888</span>, picture=/pictures/msmith/avatar/<span class="hljs-number">123454647</span>_gfas.png
</code></pre>
<p>That’s All Folks! We’ve reached the end of the first part of the introduction to the <strong>Room Persistence Library</strong>. I hope you’ve enjoyed the post and you can’t wait for more.<br />The second part will cover some details of <code>@Entities</code><strong>,</strong> we will learn how to use TypeConverters and Embedded Entities.</p>
<p><strong>Cheers!</strong></p>
<blockquote>
<p><em>This post was originally published on</em><a target="_blank" href="https://speednet.pl/blog/room-persistence-library-introduction-part-1/"><em>Speednet blog 16.10.201</em></a><em>8</em></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Room Persistence Library Introduction — part 2]]></title><description><![CDATA[Learn about Room Embedded Entities, Type Converters, Migrations, and database testing in the second part of this Room Persistence Library series]]></description><link>https://michalkonkel.dev/room-persistence-library-introduction-part-2</link><guid isPermaLink="true">https://michalkonkel.dev/room-persistence-library-introduction-part-2</guid><category><![CDATA[Android]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Tue, 16 Oct 2018 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720690126668/41960fb2-efe5-4ef6-9dcd-c10ec2c29cb5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This article is the second part of the three-part series that will smoothly introduce</em> <strong><em>Room Persistence Library</em></strong> <em>to you.</em> In this part we will learn about Room Embedded Entities and Type Converters — to achieve that we will also pay attention to Migrations, in the end we will add some tests to the project.</p>
<p>Part 1 can be found <a target="_blank" href="https://michalkonkel.dev/room-persistence-library-introduction-part-1"><strong>here</strong></a> — it was focused on configuring the project and explaining the basic structures.</p>
<p>Please remember that all sources can be found in the related <a target="_blank" href="https://github.com/mkonkel/RoomBeginners"><strong><em>GitHub</em></strong></a> project.</p>
<h1 id="heading-basic-elements-continuation"><strong>Basic elements — continuation</strong></h1>
<h2 id="heading-embedded-entity"><code>@Embedded — Entity</code></h2>
<p>Besides previously described elements we should take a look at the <code>@Embedded</code> annotation that will allow us to simplify a bit our complex dataset and “flatten” the DB structure.</p>
<p>In some cases, you would like to query a single entity that contains a few independent objects. Instead of creating a separate entity for every linked object you can use <code>@Embedded</code> annotation that will allow you to store them as subfields of the parent entity.</p>
<p>For example, we can add the <strong>Address</strong> field to our <strong>User</strong> class. Instead of creating a separate entity and adding a relation to them we will do as follows. Let’s go to <strong>User</strong> class and add another data class inside the existing one — an <strong>Address</strong> class.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Address</span></span>(
        <span class="hljs-keyword">val</span> street: String,
        <span class="hljs-keyword">val</span> city: String,
        <span class="hljs-keyword">val</span> postal: String
)
</code></pre>
<p>As you can see we can still use features like <code>@ColumnInfo</code>. Now, let’s assign an <strong>Address</strong> to the <strong>User</strong>.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Embedded</span>
<span class="hljs-keyword">var</span> address: Address,
</code></pre>
<p>If we would like to add more than one address we should make use of the prefix field. Please note that prefix is always applied to subfields even if they have a <code>@ColumnInfo</code> with a specific name. If subfields of an embedded field have <code>@PrimaryKey</code> annotation, they will not be considered as primary keys in the owner Entity.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Embedded(prefix = <span class="hljs-meta-string">"home_"</span>)</span>
<span class="hljs-keyword">var</span> homeAddress: Address,

<span class="hljs-meta">@Embedded(prefix = <span class="hljs-meta-string">"office_"</span>)</span>
<span class="hljs-keyword">var</span> officeAddress: Address,
</code></pre>
<p>The table representing a <strong>User</strong> will now also contain the columns with the following names:</p>
<p><em>home_street</em>,<br /><em>home_city</em>,<br /><em>home_postal_code</em>,<br /><em>office_street</em>,<br /><em>office_city</em>,<br /><em>office_postal_code</em>.</p>
<p>You need to decide which solution fits your needs if an embedded entity is sufficient and will not cause any errors and you think you really need this extra DB column for storing address only?</p>
<h1 id="heading-typeconverter"><code>@TypeConverter</code></h1>
<p>Sometimes, your app needs to use a custom data type whose value you would like to store in a single database column or you just can’t store the preferred type in SQLite. The solution is <code>@TypeConverter</code> which converts a custom class to and from a known type that Room can persist.</p>
<p>For example, if we want to persist instances of Date, we can write the following TypeConverter to store the equivalent Unix timestamp in the database.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DateTypeConverter</span> </span>{
    <span class="hljs-meta">@TypeConverter</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fromTimestamp</span><span class="hljs-params">(value: <span class="hljs-type">String</span>?)</span></span>: LocalDate? {
        <span class="hljs-keyword">return</span> value?.let {  LocalDate.parse(value) }
    }

    <span class="hljs-meta">@TypeConverter</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">dateToTimestamp</span><span class="hljs-params">(date: <span class="hljs-type">LocalDate</span>?)</span></span>: String? {
        <span class="hljs-keyword">return</span> date.toString()
    }
}
</code></pre>
<p>We need to define two functions, one that converts a LocalDate object to a String object and another that performs the inverse conversion, from String to LocalDate. Since Room already knows how to persist String objects, it can use this converter to persist values of LocalDate type.</p>
<p>The TypeConverter is added to the scope of the element so if you put it on a class, all methods/fields in that class will be able to use the converters.</p>
<ul>
<li><p>If you put it on a Database, all Daos and Entities in that database will be able to use it.</p>
</li>
<li><p>If you put it on a Dao, all methods in the Dao will be able to use it.</p>
</li>
<li><p>If you put it on an Entity, all fields of the Entity will be able to use it.</p>
</li>
<li><p>If you put it on a POJO, all fields of the POJO will be able to use it.</p>
</li>
<li><p>If you put it on an Entity field, only that field will be able to use it.</p>
</li>
<li><p>If you put it on a Dao method, all parameters of the method will be able to use it.</p>
</li>
<li><p>If you put it on a Dao method parameter, just that field will be able to use it.</p>
</li>
</ul>
<p>Such a converter will be useful in the whole application — let’s add it to the database class then.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Database(
        entities = [User::class],
        version = AppDatabase.DB_VERSION
)</span>
<span class="hljs-meta">@TypeConverters(DateTypeConverter::class)</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppDatabase</span> : <span class="hljs-type">RoomDatabase</span></span>()
</code></pre>
<p>Now we can think about some custom type converter, let’s try to store an enum. First of all, let’s create the enum, it should be localised inside the User class, for this example let’s assume that every user account can be active, pending (waiting for confirmation) or blocked, to avoid nulls we will add also the unknown status.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">enum</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Status</span></span>(<span class="hljs-keyword">val</span> code: <span class="hljs-built_in">Int</span>) {
    ACTIVE(<span class="hljs-number">0</span>),
    PENDING(<span class="hljs-number">1</span>),
    BLOCKED(<span class="hljs-number">3</span>),
    UNKNOWN(-<span class="hljs-number">1</span>)
}
</code></pre>
<p>Now we need to add a proper TypeConverter.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserStatusTypeConverter</span> </span>{
    <span class="hljs-meta">@TypeConverter</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fromInteger</span><span class="hljs-params">(value: <span class="hljs-type">Int</span>)</span></span>: User.Status {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">when</span> (value) {
            <span class="hljs-number">0</span> -&amp;gt; User.Status.ACTIVE
            <span class="hljs-number">1</span> -&amp;gt; User.Status.PENDING
            <span class="hljs-number">2</span> -&amp;gt; User.Status.BLOCKED
            <span class="hljs-keyword">else</span> -&amp;gt; User.Status.UNKNOWN
        }
    }

    <span class="hljs-meta">@TypeConverter</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">statusToInteger</span><span class="hljs-params">(status: <span class="hljs-type">User</span>.<span class="hljs-type">Status</span>)</span></span>: <span class="hljs-built_in">Int</span> {
        <span class="hljs-keyword">return</span> status.code
    }
}
</code></pre>
<p>As mentioned before now we need to add this converter to the scope, this case is related only to the User entity so we will add this only to the entity, also we created this class inside the <code>User.kt</code> file.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity(tableName = <span class="hljs-meta-string">"users"</span>)</span>
<span class="hljs-meta">@TypeConverters(UserStatusTypeConverter::class)</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>( 
   … 
)
</code></pre>
<p>Let’s extend the User entity with given properties.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>(
       ….

        <span class="hljs-keyword">var</span> birthday: LocalDate?,

        <span class="hljs-keyword">var</span> status: Status

       ….
)
</code></pre>
<p>With the power of TypeConverter you can store any type of data. If you want to persist a collection of objects you can use Gson and map them to JSON etc. Let’s try our code and run the App… and we’ve got a crash. The stack trace is pretty obvious and tells us what to do.</p>
<pre><code class="lang-kotlin">Room cannot verify the <span class="hljs-keyword">data</span> integrity. Looks like you<span class="hljs-string">'ve changed schema but forgot to update the version number. 
You can simply fix this by increasing the version number.</span>
</code></pre>
<p>If our App is still in development — that’s OK, but what if our app is in production and we can’t just upgrade the DB version and erase previously stored data during DB update? We need to write a Migration!</p>
<h1 id="heading-migrations"><strong>Migrations</strong></h1>
<p>So, as you can easily deduce when your entity classes change or you add new tables to the existing DB the old schema doesn’t fit the new one. When it comes to updating the app to the latest version and you don’t want to lose the existing data you need to write a migration. In any other case, you can just increase DB version and Room will recreate DB schema with new values.</p>
<p>To put it simply, a migration is an operation that will adjust existing DB and data to the latest changes in a schema (your entities and tables in code).</p>
<p>In this manner <strong>Room Persistence Library</strong> allows you to write <strong>Migration</strong>classes to preserve user data. Each Migration class specifies a <strong><em>startVersion</em></strong>and <strong><em>endVersion</em></strong>. At runtime, Room runs each <strong><em>migrate()</em></strong> method, using the correct order to migrate the database to a later version. A Migration class defines the actions that should be performed when migrating from one specific version to another.</p>
<p>A migration can handle more than one version (if you have a faster path to choose when going from version 3 to 5 without going to version 4). If Room opens a database at version 3 and the latest version is &gt;= 5, Room will use the migration object that can migrate from 3 to 5 instead of 3 to 4 and 4 to 5.</p>
<p>If there are not enough migrations provided to move from the current version to the latest version, Room will clear the database and recreate it so even if you have no changes between 2 versions, you should still provide a Migration object to the builder.</p>
<p>If you don’t want to write any migrations just call the <strong><em>fallbackToDestructiveMigration</em></strong> in the database builder — all tables will be dropped and recreated.</p>
<p>Let’s add some code! First, create an object Migration where we will store all of our migrations and then add there a value as follows.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">object</span> Migrations {

    <span class="hljs-keyword">val</span> MIGRATION_1_2: Migration = <span class="hljs-keyword">object</span> : Migration(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>) {
        <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">migrate</span><span class="hljs-params">(database: <span class="hljs-type">SupportSQLiteDatabase</span>)</span></span> {
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN birthday TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN home_street TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN home_city TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN home_postalCode TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN office_street TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN office_city TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN office_postalCode TEXT"</span>)
            database.execSQL(<span class="hljs-string">"ALTER TABLE `users` ADD COLUMN status INTEGER NOT NULL DEFAULT -1"</span>)
        }
    }
}
</code></pre>
<p>Since SQLite doesn’t support multiple ADD calls we need to do it one by one.</p>
<p>Now we need to increase the DB version and add the migration above to DB — to do this, we need to modify the AppDatabase class as follows:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">val</span> DB_VERSION = <span class="hljs-number">2</span>

...

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">buildDatabase</span><span class="hljs-params">(context: <span class="hljs-type">Context</span>)</span></span> =
            Room.databaseBuilder(context.applicationContext, AppDatabase::<span class="hljs-keyword">class</span>.java, DB_NAME)
                    .addCallback(dbCreateCallback(context))
                    .addMigrations(Migrations.MIGRATION_1_2)
                    .build()
...

}
</code></pre>
<p>Now we can run our App, if everything went OK we should see logs similar to these:</p>
<pre><code class="lang-kotlin">User(id=<span class="hljs-number">1</span>, firstName=John, lastName=Doe, fullName=John Doe, birthday=<span class="hljs-literal">null</span>, homeAddress=<span class="hljs-literal">null</span>, officeAddress=<span class="hljs-literal">null</span>, emailAddress=<span class="hljs-symbol">jdoe@</span>mail.com, phoneNumber=<span class="hljs-number">001333444555</span>, picture=/pictures/jdoe/avatar/s34trag_732_jkdal.png, status=UNKNOWN)

User(id=<span class="hljs-number">2</span>, firstName=Mark, lastName=Smith, fullName=Mark Smith, birthday=<span class="hljs-literal">null</span>, homeAddress=<span class="hljs-literal">null</span>, officeAddress=<span class="hljs-literal">null</span>, emailAddress=<span class="hljs-symbol">mastermike@</span>mail.com, phoneNumber=<span class="hljs-number">001666999888</span>, picture=/pictures/msmith/avatar/<span class="hljs-number">123454647</span>_gfas.png, status=UNKNOWN)

User(id=<span class="hljs-number">3</span>, firstName=John, lastName=Doe, fullName=John Doe, birthday=<span class="hljs-literal">null</span>, homeAddress=<span class="hljs-literal">null</span>, officeAddress=<span class="hljs-literal">null</span>, emailAddress=<span class="hljs-symbol">jdoe@</span>mail.com, phoneNumber=<span class="hljs-number">001333444555</span>, picture=/pictures/jdoe/avatar/s34trag_732_jkdal.png, status=UNKNOWN)

User(id=<span class="hljs-number">4</span>, firstName=Mark, lastName=Smith, fullName=Mark Smith, birthday=<span class="hljs-literal">null</span>, homeAddress=<span class="hljs-literal">null</span>, officeAddress=<span class="hljs-literal">null</span>, emailAddress=<span class="hljs-symbol">mastermike@</span>mail.com, phoneNumber=<span class="hljs-number">001666999888</span>, picture=/pictures/msmith/avatar/<span class="hljs-number">123454647</span>_gfas.png, status=UNKNOWN)
</code></pre>
<p>For better DB investigation I heartily encourage you to use Facebooks Stetho library — <a target="_blank" href="http://facebook.github.io/stetho/">http://facebook.github.io/stetho/</a> adding it to the project is pretty straightforward, just add proper dependency and initialize it in Application class.</p>
<p>As you can see in logs or stetho — there are no values for the new fields even though you added them to prepopulated data — you ask why? — It’s because the callback where we are adding this data is invoked only when DB is first created — now we have just modified existing DB.</p>
<p>As you can see we put the “-1” value as the default for the status column and a rule for the StatusTypeConverter that will map integers to enums. We can see that it works perfectly — every user has an UNKNOWN status!</p>
<h1 id="heading-testing-the-database"><strong>Testing the database</strong></h1>
<h1 id="heading-entity"><code>@Entity</code></h1>
<p>Instead of running the app all the time to check if new queries work OK or a migration was successful — we should write a test to speed up our work.</p>
<p>The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don’t require creating an activity, they should be faster to execute than your UI tests.</p>
<p>Let’s focus on the User Entity. First of all, we need to create a test class and prepare it to use with our database.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@RunWith(AndroidJUnit4::class)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserEntityTest</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> userDao: UserDao
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> database: AppDatabase

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">createDb</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">val</span> context = InstrumentationRegistry.getTargetContext()
        database = Room.inMemoryDatabaseBuilder(context, AppDatabase::<span class="hljs-keyword">class</span>.java).build()

        userDao = database.userDao()
    }
…
}
</code></pre>
<p><strong><em>inMemoryDatabaseBuilder</em></strong> creates a <strong><em>RoomDatabase.Builder</em></strong> for a in-memory database. Information stored in a in-memory database disappears when the process is killed. Once a database is built, you should keep a reference to it and re-use it. We need to remember to close the database after all tests.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@After</span>
 <span class="hljs-meta">@Throws(IOException::class)</span>
 <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">closeDb</span><span class="hljs-params">()</span></span> {
     database.close()
 }
</code></pre>
<p>As we are ready to go we can add some tests that will check if our database works correctly against some typical database actions insert, update and read.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Test</span>
<span class="hljs-meta">@Throws(Exception::class)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insertUserAndRead</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> user = UserData.createUserWithIndex(<span class="hljs-number">1</span>)
    userDao.insertUser(user)

    <span class="hljs-keyword">val</span> result = userDao.user(<span class="hljs-number">1</span>)

    assertEquals(result.firstName, user.firstName)
}

<span class="hljs-meta">@Test</span>
<span class="hljs-meta">@Throws(Exception::class)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insertUpdateAndRead</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> user = UserData.createUserWithIndex(<span class="hljs-number">1</span>)
    userDao.insertUser(user)

    <span class="hljs-keyword">val</span> queryUser = userDao.user(<span class="hljs-number">1</span>)
    userDao.updateUser(queryUser.apply { firstName = <span class="hljs-string">"John"</span> })

    <span class="hljs-keyword">val</span> result = userDao.user(<span class="hljs-number">1</span>)

    assertEquals(result.firstName, <span class="hljs-string">"John"</span>)
}

<span class="hljs-meta">@Test</span>
<span class="hljs-meta">@Throws(Exception::class)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insertAndDelete</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> user = UserData.createUserWithIndex(<span class="hljs-number">1</span>)
    userDao.insertUser(user)

    userDao.deleteUser(user)

    <span class="hljs-keyword">val</span> result = userDao.user(<span class="hljs-number">1</span>)

    assertNull(result)
}
</code></pre>
<p>That was quite easy, similarly we can handle migrations.</p>
<h1 id="heading-migrations-1"><strong>Migrations</strong></h1>
<p>Instead of testing migrations at the runtime, we can add some tests that will perform the following actions:</p>
<ul>
<li><p>Create Db at given version</p>
</li>
<li><p>Run migration scripts</p>
</li>
<li><p>Validate the schema</p>
</li>
</ul>
<p>Everything room needs to perform the test is written down in the JSON schema file, we only need to take care of the file — let’s add some code to app/build.gradle to fulfill this requirement.</p>
<pre><code class="lang-kotlin">android {
 …

 defaultConfig {
    javaCompileOptions {
      annotationProcessorOptions {
        arguments = [<span class="hljs-string">"room.schemaLocation"</span>:
                             <span class="hljs-string">"<span class="hljs-variable">$projectDir</span>/schemas"</span>.toString()]
      }
    }
  }

  sourceSets {
    androidTest.assets.srcDirs +=
            files(<span class="hljs-string">"<span class="hljs-variable">$projectDir</span>/schemas"</span>.toString())
  }
…

}

…

androidTestImplementation <span class="hljs-string">"android.arch.persistence.room:testing:<span class="hljs-variable">$room_version</span>"</span>
</code></pre>
<p>After adding dependencies we need to create a new test class with special <strong>@Rule</strong> with <strong><em>MigrationTestHelper</em></strong> that will take care of all the boilerplate code related to maintaining the DB.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Rule</span>
<span class="hljs-keyword">val</span> testHelper: MigrationTestHelper = MigrationTestHelper(
        InstrumentationRegistry.getInstrumentation(),
        AppDatabase::<span class="hljs-keyword">class</span>.java.canonicalName,
        FrameworkSQLiteOpenHelperFactory()
}
</code></pre>
<p>Our migration test can look like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Test</span>
<span class="hljs-meta">@Throws(Exception::class)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">migration_1_2</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> db_v_1 = testHelper.createDatabase(TEST_DB_NAME, <span class="hljs-number">1</span>)
    testHelper.runMigrationsAndValidate(TEST_DB_NAME, <span class="hljs-number">2</span>, <span class="hljs-literal">true</span>, Migrations.MIGRATION_1_2)
}
</code></pre>
<p>Please keep in mind that this isn’t validating the data consistency, this will only check the migration process. If you want to check the data integrity you need to add it manually.</p>
<p>That’s All Folks! We’ve reached the end of the second part of the introduction to the Room Persistence Library. I hope you have enjoyed this post and you can’t wait for more.<br />The third part will be about DB relations and the complex data queries.</p>
<p>Cheers!</p>
<p><em>This post was originally published on</em><a target="_blank" href="https://speednet.pl/blog/room-persistence-library-introduction-part-2/"><em>Speednet blog</em></a><em>on 16.10.2018</em></p>
]]></content:encoded></item><item><title><![CDATA[Room Persistence Library Introduction – part 3]]></title><description><![CDATA[Learn to establish table relationships, query properly, and handle various relation types in Android with Room Persistence Library]]></description><link>https://michalkonkel.dev/room-persistence-library-introduction-part-3</link><guid isPermaLink="true">https://michalkonkel.dev/room-persistence-library-introduction-part-3</guid><category><![CDATA[Android]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Michał Konkel]]></dc:creator><pubDate>Tue, 16 Oct 2018 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720693211223/5e5ff74b-ddd3-4d36-9584-921106c49228.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This article is the third and the last part of the three-part series that will smoothly introduce<strong><strong>Room Persistence Library</strong></strong>to you. In this part, I will show you how to add relations between tables/entities and how to query them properly.</em></p>
<p>Part 1 can be found <a target="_blank" href="https://michalkonkel.dev/room-persistence-library-introduction-part-1">here</a> <em>– it was focused on configuring the project and explaining the basic structures.<br />Part 2 can be found</em> <a target="_blank" href="https://michalkonkel.dev/room-persistence-library-introduction-part-2"><em>here</em></a> <em>– it was focused on</em><code>@Embedded</code><em>entities and</em><code>@TypeConverters</code><strong><em>.</em></strong></p>
<p>All sources can be found in related <a target="_blank" href="https://github.com/mkonkel/RoomBeginners"><strong><em>GitHub</em></strong></a> project.</p>
<h3 id="heading-the-room-doesnt-allow-object-references"><strong>The Room doesn’t allow object references</strong></h3>
<p>Because <strong>SQLite</strong> is a relational database, you can specify relationships between objects. Even though most object-relational mapping libraries allow entity objects to reference each other, Room explicitly forbids this. Working with <strong>Room</strong> relations is a bit tricky. Common ORMs allow you to use object references and thus ORMs implement <strong>lazy loading</strong> which was considered as potentially dangerous in Android apps.</p>
<p>UI needs approximately <strong>~16ms</strong> to calculate and draw an updated Activity layout – so if you add to this a lazy loading call for some entity field that can take ~5ms you can run of out time to draw an updated frame for Activity.</p>
<p>For example, let`s assume that we can add object reference</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span></span>(
       <span class="hljs-meta">@Id</span> <span class="hljs-keyword">var</span> id: <span class="hljs-built_in">Long</span>,
       <span class="hljs-keyword">var</span> title: String
       <span class="hljs-keyword">var</span> authorId: <span class="hljs-built_in">Long</span>,
       <span class="hljs-meta">@ToOne(joinProperty=<span class="hljs-meta-string">"authorId"</span>)</span>
       <span class="hljs-keyword">var</span> author: Author
)
</code></pre>
<p>and</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span></span>(
        <span class="hljs-meta">@Id</span> <span class="hljs-keyword">var</span> id: <span class="hljs-built_in">Long</span>,
        <span class="hljs-keyword">var</span> name: String
)
</code></pre>
<p>In such construction and lazy loading, Book will use <strong><em>getAuthor()</em></strong> method to return the author – the first call of this method will query DB for the corresponding <strong>Author</strong>.<br />Now if you try to set a text on the <strong>TextView</strong> and you need an authors name you will write something like this:</p>
<pre><code class="lang-kotlin">textView.text = book.getAuthor().getName()
</code></pre>
<p>This will invoke another query to get the author’s name – on the <strong>main thread</strong>! This can end up with glitches in your app UI.</p>
<p>So, on the other hand instead of lazy loading we can use eager loading and load all necessary data earlier – but this will cause the overloading of the data and we will load something that isn’t needed in current point of the app.</p>
<p><strong>To sum this up:</strong><br />We can use <strong>Lazy Loading</strong> that will allow our app to query faster, load fewer data and improve the performance – but we can struggle with querying on UI thread and risk the glitches.<br />We can also use Eager loading where we lose all the performance gain, and we will load big amounts of useless data.</p>
<p>The Room comes across with something that mixes these two approaches. To reference multiple entities at the same time we need to create a <strong>POJO</strong> that contains each entity and write a query that will join corresponding tables.</p>
<p>Even though you cannot use direct relationships, Room still allows you to define Foreign Key constraints between entities.</p>
<p>Let’s add some code! We will add <strong>Book</strong> entity.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity(tableName = <span class="hljs-meta-string">"books"</span>,
        foreignKeys = [ForeignKey(
                entity = User::class,
                parentColumns = [<span class="hljs-meta-string">"id"</span>],
                childColumns = [<span class="hljs-meta-string">"user_id"</span>],
                onDelete = ForeignKey.NO_ACTION
        )</span>]
)
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span></span>(
        <span class="hljs-meta">@PrimaryKey(autoGenerate = true)</span>
        <span class="hljs-keyword">var</span> id: <span class="hljs-built_in">Long</span>,
        <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"user_id"</span>)</span>
        <span class="hljs-keyword">var</span> userId: <span class="hljs-built_in">Long</span>?,
        <span class="hljs-keyword">var</span> title: String,
        <span class="hljs-meta">@Embedded(prefix = <span class="hljs-meta-string">"author_"</span>)</span>
        <span class="hljs-keyword">var</span> author: Author

) {
    <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span></span>(
            <span class="hljs-keyword">var</span> firstName: String,
            <span class="hljs-keyword">var</span> lastName: String
    )
}
</code></pre>
<p>Even though you cannot use direct relationships, Room still allows you to define <strong>ForeignKey</strong>constraints between entities. Using the <strong>ForeingKey</strong> allows you to decide what should happen with the entity when the corresponding parent is deleted.</p>
<p>Don’t forget to add a migration to the DB (or you can just remove the existing app from the device or emulator and run the project again!)</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> MIGRATION_2_3: Migration = <span class="hljs-keyword">object</span> : Migration(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) {
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">migrate</span><span class="hljs-params">(database: <span class="hljs-type">SupportSQLiteDatabase</span>)</span></span> {
        database.execSQL(
                <span class="hljs-string">"CREATE TABLE 'books' ('id' INTEGER NOT NULL, 'user_id' INTEGER, 'title' TEXT, 'author_firstName' TEXT, 'author_lastName' TEXT, FOREIGN KEY('user_id') REFERENCES users('id'), PRIMARY KEY('id'))"</span>
        )
    }
}
</code></pre>
<p>The database:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Database(
        entities = [User::class, Book::class], 
//...
        const val DB_VERSION = 3
//...
      .addMigrations(Migrations.MIGRATION_2_3)</span>
<span class="hljs-comment">//...</span>
</code></pre>
<p>Don`t forget to create corresponding <strong>DAO</strong> and a prepopulating object.</p>
<h3 id="heading-one-to-many-relation"><strong>One-to-many relation</strong></h3>
<p>First of all, let’s focus on one-to-many relation – this will require a special <strong>POJO</strong> (because Room doesn’t allow object relations) – so we should create the UserWithAllBooks class and simple query.</p>
<p>Let`s start with a <strong>POJO</strong>:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserWithAllBooks</span> </span>{
    <span class="hljs-meta">@Embedded</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> user: User
    <span class="hljs-meta">@Transaction</span>
    <span class="hljs-meta">@Relation(parentColumn = <span class="hljs-meta-string">"id"</span>, entityColumn = <span class="hljs-meta-string">"user_id"</span>, entity = Book::class)</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> books: List&amp;lt;Book&amp;gt;
}
</code></pre>
<p>The class above will use a @Relation annotation which can be used in a <strong>POJO</strong> to fetch relation entities automatically. When the POJO is returned from a query, all of its relations are also fetched by Room. This annotation must be a List or Set.</p>
<p><code>@Transaction</code> annotation should be used in two cases:</p>
<ul>
<li><p>If the query is fairly big, it is better to run it inside a transaction to receive a consistent result. Otherwise, the query result does not fit into a single CursorWindow.<br />  When you use @Relation annotation in POJO class because then all fields are queried separately, so when you want to receive consistent results between these queries it’s a good idea to do them in the transaction.</p>
</li>
<li><p>If the result of the query is a POJO with Relation fields, these fields are queried separately. To receive consistent results between these queries, you probably want to run them in a single transaction.</p>
</li>
</ul>
<p>The UserWithAllBooks is just a common POJO but all of the fields are fetched from the entity defined in the <code>@Relation</code> (<strong>Book</strong>).<br />The <code>@Embedded</code> annotation will give us a direct access to the fields of the embedded data type (<strong>User</strong>). Usage of <code>@Embedded</code> annotation is dictated by Kotlin.</p>
<p><code>@Relation</code> annotation can be used only on <strong>POJO</strong> classes – that means that you can`t use it with <code>@Entity</code> (it’s a room design decision) – so to build a relation as above you can just simply extend the desired entity so it can look like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserWithAllBooksJava</span> : <span class="hljs-type">User</span></span>() {
    <span class="hljs-meta">@Relation(parentColumn = <span class="hljs-meta-string">"id"</span>, entityColumn = <span class="hljs-meta-string">"user_id"</span>, entity = Book::class)</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> books: List&amp;lt;Book&amp;gt;
}
</code></pre>
<p>But in <strong>Kotlin</strong> you can’t inherit from data class – so usage of <code>@Embedded</code> annotation is a Kotlin workaround for <code>@Relation</code> limitation workaround…</p>
<p>Now let’s construct a proper query. The Room allows you to pass parameters into queries to perform filtering operations, such as finding a user by Id or displaying only users live in a certain city, it is as simple as that:</p>
<pre><code class="lang-sql">@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = :userId <span class="hljs-keyword">LIMIT</span> <span class="hljs-number">1</span><span class="hljs-string">")
fun getUserWithBooksById(userId: Long): UserWithAllBooks</span>
</code></pre>
<p>When this query is processed at compile time, Room matches the :<strong><em>userId</em></strong> bind parameter with the userId method parameter. Room performs the match using the parameter names. If there is a mismatch, an error occurs as your app compiles. The keyword LIMIT will assure us that we will get only one user in this query.</p>
<h2 id="heading-one-to-one-relation"><strong>One-to-one relation</strong></h2>
<p>Now we will add <strong>Category</strong> entity and create <strong>one-to-one</strong> relation – with an assumption that one book can have only one category. The process will be much similar to the one-to-many relation but instead of a List, we will add a relation to the single object. This is a rather rare DB relation type, but still, you might need it.</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity(tableName = <span class="hljs-meta-string">"categories"</span>)</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Category</span></span>(
        <span class="hljs-meta">@PrimaryKey(autoGenerate = true)</span>
        <span class="hljs-keyword">var</span> id: <span class="hljs-built_in">Long</span>,

        <span class="hljs-meta">@TypeConverters(CategoryNameTypeConverter::class)</span>
        <span class="hljs-keyword">var</span> name: Name
) {
    <span class="hljs-keyword">enum</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span></span>(<span class="hljs-keyword">val</span> code: <span class="hljs-built_in">Int</span>) {
        COMEDY(<span class="hljs-number">0</span>),
        DRAMA(<span class="hljs-number">1</span>),
        FANTASY(<span class="hljs-number">2</span>),
        ROMANCE(<span class="hljs-number">3</span>),
        SCIENCE(<span class="hljs-number">4</span>),
        UNKNOWN(-<span class="hljs-number">1</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CategoryNameTypeConverter</span> </span>{
    <span class="hljs-meta">@TypeConverter</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">fromInteger</span><span class="hljs-params">(value: <span class="hljs-type">Int</span>)</span></span>: Category.Name {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">when</span> (value) {
            <span class="hljs-number">0</span> -&amp;gt; Category.Name.COMEDY
            <span class="hljs-number">1</span> -&amp;gt; Category.Name.DRAMA
            <span class="hljs-number">2</span> -&amp;gt; Category.Name.FANTASY
            <span class="hljs-number">3</span> -&amp;gt; Category.Name.ROMANCE
            <span class="hljs-number">4</span> -&amp;gt; Category.Name.SCIENCE
            <span class="hljs-keyword">else</span> -&amp;gt; Category.Name.UNKNOWN
        }
    }

    <span class="hljs-meta">@TypeConverter</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">statusToInteger</span><span class="hljs-params">(category: <span class="hljs-type">Category</span>.<span class="hljs-type">Name</span>)</span></span>: <span class="hljs-built_in">Int</span> {
        <span class="hljs-keyword">return</span> category.code
    }
}
</code></pre>
<p>We also need to add another ForeignKey to Book entity:</p>
<pre><code class="lang-kotlin">ForeignKey(
    entity = Category::<span class="hljs-class"><span class="hljs-keyword">class</span>,
    <span class="hljs-type">parentColumns = arrayOf</span></span>(<span class="hljs-string">"id"</span>),
    childColumns = arrayOf(<span class="hljs-string">"category_id"</span>),
     onDelete = ForeignKey.NO_ACTION
)

<span class="hljs-comment">//…</span>

  <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"category_id"</span>)</span>
  <span class="hljs-keyword">var</span> categoryId: <span class="hljs-built_in">Long</span>?,
</code></pre>
<p>And a migration</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> MIGRATION_3_4: Migration = <span class="hljs-keyword">object</span> : Migration(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>) {
      <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">migrate</span><span class="hljs-params">(database: <span class="hljs-type">SupportSQLiteDatabase</span>)</span></span> {
          database.execSQL(
                  <span class="hljs-string">"CREATE TABLE 'categories' ('id'  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 'name' INTEGER NOT NULL)"</span>)
          database.execSQL(<span class="hljs-string">"INSERT INTO categories (name) VALUES (0),(1),(2),(3),(4),(5),(-1)"</span>)

          <span class="hljs-comment">//Because of https://www.sqlite.org/omitted.html</span>
          database.execSQL(
                  <span class="hljs-string">"CREATE TABLE 'books_new' ('id' INTEGER NOT NULL, 'user_id' INTEGER, 'category_id' INTEGER, 'title' TEXT, 'author_firstName' TEXT, 'author_lastName' TEXT, FOREIGN KEY('user_id') REFERENCES users('id'), FOREIGN KEY('category_id') REFERENCES categories('id'), PRIMARY KEY('id'))"</span>)
          database.execSQL(<span class="hljs-string">"INSERT INTO books_new(id, user_id, category_id, title, author_firstName, author_lastName) SELECT id, user_id, -1, title, author_firstName, author_lastName FROM books"</span>)
          database.execSQL(<span class="hljs-string">"DROP TABLE books"</span>)
          database.execSQL(<span class="hljs-string">"ALTER TABLE books_new RENAME TO books"</span>)
      }
}
</code></pre>
<p>We also need to add a POJO class for catching the query result:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookWithCategory</span> </span>{
    <span class="hljs-meta">@Embedded</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> book: Book

    <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"name"</span>)</span>
    <span class="hljs-meta">@TypeConverters(CategoryNameTypeConverter::class)</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> category: Category.Name
}
</code></pre>
<p>As you can see now we are not using the <code>@Relation</code> annotation, because this is a <strong>one-to-one</strong>relation and mentioned annotation can be applied only to List or Set.</p>
<p>As you can easily notice we are using <code>@ColumnInfo</code> on non-entity class – this is for our convenience – without this annotation, Room wouldn’t know which column from returned query it should use, also thanks to this we can easily change the returning values names.</p>
<p>We also need to use <code>@TypeConverter</code> with proper class. We can avoid adding it here when we move this converter to Database level, not Entity or POJO.</p>
<p>Used query:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM books JOIN categories ON books.category_id = categories.id WHERE books.id = :bookID"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getBookWithCategory</span><span class="hljs-params">(bookID: <span class="hljs-type">Long</span>)</span></span>: BookWithCategory

<span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM books JOIN categories ON books.category_id = categories.id"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setBooksWithCategories</span><span class="hljs-params">()</span></span>: List&amp;lt;BookWithCategory&amp;gt;
</code></pre>
<p>This case will also work fine without <code>@ColumnInfo</code> annotation, it just needs some small modifications:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookWithCategorySimple</span> </span>{
    <span class="hljs-meta">@Embedded</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> book: Book

    <span class="hljs-meta">@TypeConverters(CategoryNameTypeConverter::class)</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> category: Category.Name
}
</code></pre>
<p>And we also need to upgrade our query:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT *, categories.name AS category FROM books JOIN categories ON books.category_id = categories.id"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setBooksWithCategoriesSimple</span><span class="hljs-params">()</span></span>: List&amp;lt;BookWithCategorySimple&amp;gt;
</code></pre>
<p>The results in our TestActivity will be the same.<br />It’s your choice which way you want to design your queries, and how to handle relations, but remember about <code>@Transaction</code>.</p>
<p>Please don’t forget to update PrepopulateData and create the <strong>CategoryDao</strong> – it should be needed while prepopulating DB.</p>
<h2 id="heading-many-to-many-relation"><strong>Many-to-many relation</strong></h2>
<p>In SQL, implementing M:N relations requires a join table of some form, where the join table has foreign keys back to the entities being related. Room, using SQL at its core, does not change this. And since Room does not model relations, but only foreign keys, to create an M:N relation, you have to create a “join entity” that winds up creating the associated join table.</p>
<p>Regarding our simple App let’s assume that every user can attend a class (subjects) – we need to create a simple entity that will represent the subject, and joined entity <strong>users_with_subjects.</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity(tableName = <span class="hljs-meta-string">"subjects"</span>)</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Subject</span></span>(
        <span class="hljs-meta">@PrimaryKey(autoGenerate = true)</span>
        <span class="hljs-keyword">var</span> id: <span class="hljs-built_in">Long</span>,

        <span class="hljs-keyword">var</span> name: String
)
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Entity(tableName = <span class="hljs-meta-string">"users_with_subjects"</span>,
        primaryKeys = [<span class="hljs-meta-string">"user_id"</span>, <span class="hljs-meta-string">"subject_id"</span>],
        foreignKeys = [
            ForeignKey(
                    entity = User::class,
                    parentColumns = arrayOf(<span class="hljs-meta-string">"id"</span>)</span>,
                    childColumns = arrayOf(<span class="hljs-string">"user_id"</span>)
            ),
            ForeignKey(
                    entity = Subject::<span class="hljs-class"><span class="hljs-keyword">class</span>,
                    <span class="hljs-type">parentColumns = arrayOf</span></span>(<span class="hljs-string">"id"</span>),
                    childColumns = arrayOf(<span class="hljs-string">"subject_id"</span>)
            )
        ]
)
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UsersWithSubjects</span></span>(
        <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"user_id"</span>)</span>
        <span class="hljs-keyword">var</span> userId: <span class="hljs-built_in">Long</span>,

        <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"subject_id"</span>)</span>
        <span class="hljs-keyword">var</span> subjectId: <span class="hljs-built_in">Long</span>
)
</code></pre>
<p>It can look a bit scary but if you have a closer look everything will work well. We are using composite primary key that is created with the <strong>user_id</strong> and <strong>subject_id.</strong> This will make every pair of user_id and subject_id unique and we will avoid the duplicates. Foreign keys are straightforward. They represent both <strong>User</strong> and <strong>Subject</strong> entities ids.</p>
<p>Now with the proper DB query, we can find for example all subjects for a given user:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM subjects INNER JOIN users_with_subjects AS uws ON uws.subject_id = subjects.id INNER JOIN users ON users.id = uws.user_id WHERE users.id = :userId"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getSubjectsForUser</span><span class="hljs-params">(userId: <span class="hljs-type">Long</span>)</span></span>: List&amp;lt;Subject&amp;gt;
</code></pre>
<p>or, a list of users that should attend a given subject:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM users INNER JOIN users_with_subjects AS uws ON uws.user_id = users.id INNER JOIN subjects ON subjects.id = uws.subject_id WHERE subjects.id = :subjectId"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsersForGivenSubjects</span><span class="hljs-params">(subjectId: <span class="hljs-type">Long</span>)</span></span>: List&amp;lt;User&amp;gt;
</code></pre>
<p>Please remember about adding proper migration, prepopulated data set, entities classes to DB and increasing the DB version.</p>
<p><strong>To sum up the relations:</strong><br />The Room provides the same relation types as in <strong>SQL</strong>, however, unlike the majority of ORM’s it will not allow you to create object relation – this makes you write additional <strong>POJO</strong> class that will aggregate query results into objects. Nevertheless, you can use <code>@Relation</code> annotation to avoid complicated <strong>SELECT</strong> queries.</p>
<h2 id="heading-things-you-should-also-see"><strong>Things you should also see</strong></h2>
<ul>
<li><p>First of all, you should always query things you really need. In most cases you won’t even need the object relation and simple “id” and “name” will be suitable to meet the business rules of the app.</p>
</li>
<li><p>If possible try to use <code>@Relation</code> annotation to simplify the one-to-many relation.</p>
</li>
<li><p>Always use the foreign keys constraints between entities. This will allow you to validate data consistency when you are modifying the database use onDelete and onUpdate methods with proper actions SET_NULL, CASCADE, NO_ACTION etc…</p>
</li>
</ul>
<h3 id="heading-returning-subsets-of-columns"><strong>Returning subsets of columns:</strong></h3>
<p>We did it in previous queries but I want to show you how to work with <strong>POJO’s</strong> that are returned by the query where we don’t need the whole objects. Let’s think about users books. In most cases, we will need only the <strong><em>title</em></strong>, <strong><em>author</em></strong> and <strong><em>category</em></strong> – to show on a list. All we need is a simple <strong>POJO</strong> and a good query:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UsersBooksSimple</span> </span>{
    <span class="hljs-meta">@ColumnInfo(name = <span class="hljs-meta-string">"title"</span>)</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> name: String

    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> author: String

    <span class="hljs-meta">@TypeConverters(CategoryNameTypeConverter::class)</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> category: Category.Name
}
</code></pre>
<p>The first line is the book <strong><em>title</em></strong>, the second line will represent the author as the combination of two columns <strong><em>author_firstName</em></strong> and <strong><em>author_lastName</em></strong>, the last one is the book <strong><em>category</em></strong>.</p>
<p>If the returned column name matches the field name in <strong>POJO</strong> we don’t have to use the <code>@ColumnInfo(name= “…”)</code> annotation. In other cases we need to specify how we named the queried table, just like in the following query:</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT categories.name AS category, books.title, (books.author_firstName || "</span> <span class="hljs-meta-string">" || books.author_lastName) AS author FROM books INNER JOIN categories ON books.category_id = categories.id INNER JOIN users ON users.id = books.user_id WHERE users.id = :userId"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsersBooksSimple</span><span class="hljs-params">(userId: <span class="hljs-type">Long</span>)</span></span>: List&amp;lt;UsersBooksSimple&amp;gt;
</code></pre>
<p>As you can see we didn’t need to create a new <strong>TypeConverter</strong> to creating the author full name field – we can use the SQLite functionalities and create one field from two queried columns.</p>
<p>We can also do a similar trick with the <code>@Relation</code> annotation, let’s check how we can use projection field when defining <strong>POJO</strong>. Let’s create another class for <strong>UserWithAllBooks</strong> which contains only a book title.</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserWithAllBooksTitle</span> </span>{
    <span class="hljs-meta">@Embedded</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> user: User

    <span class="hljs-meta">@Relation(parentColumn = <span class="hljs-meta-string">"id"</span>, entityColumn = <span class="hljs-meta-string">"user_id"</span>, entity = Book::class, projection = [<span class="hljs-meta-string">"title"</span>])</span>
    <span class="hljs-keyword">lateinit</span> <span class="hljs-keyword">var</span> bookkTitle: List&amp;lt;String&amp;gt;
}
</code></pre>
<pre><code class="lang-sql">@Transaction
@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = :userId <span class="hljs-keyword">LIMIT</span> <span class="hljs-number">1</span><span class="hljs-string">")
fun getUsersBooksTitles(userId: Long): UserWithAllBooksTitle</span>
</code></pre>
<p>We can also pass multiple parameters to the query:</p>
<pre><code class="lang-sql">@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> users.firstName <span class="hljs-keyword">LIKE</span> :firstName <span class="hljs-keyword">OR</span> users.lastName <span class="hljs-keyword">LIKE</span> :lastName<span class="hljs-string">")
fun getUsersByName(firstName: String, lastName: String): List&amp;lt;User&amp;gt;</span>
</code></pre>
<p>As simple as that!<br />Everything is a matter of how you create your query.</p>
<h3 id="heading-abstract-dao-class"><strong>Abstract DAO class</strong></h3>
<p>Detailed gist can be found <a target="_blank" href="https://gist.github.com/florina-muntenescu/1c78858f286d196d545c038a71a3e864"><strong><em>here</em></strong></a>.</p>
<p>In a nutshell, instead of using interface for creating specifics DAO’s you can choose the abstract class. Then you can create methods like this:</p>
<pre><code class="lang-kotlin"> <span class="hljs-meta">@Dao</span>
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductDao</span> </span>{
    <span class="hljs-meta">@Insert</span>
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> void insert(Product product);
    <span class="hljs-meta">@Delete</span>
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> void delete(Product product);
    <span class="hljs-meta">@Transaction</span>
     <span class="hljs-keyword">public</span> void insertAndDeleteInTransaction(Product newProduct, Product oldProduct) {
         <span class="hljs-comment">// Anything inside this method runs in a single transaction.</span>
         insert(newProduct);
         delete(oldProduct);
     }
 }
</code></pre>
<p>Furthermore, if you are tired of creating same DAO methods (insert, delete etc..) you can create one generic Interface <code>BaseDao&lt;T&gt;</code> then create abstract DAO that implements this interface so you will end up like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">BaseDao</span>&amp;<span class="hljs-title">lt</span>;<span class="hljs-title">T</span>&amp;<span class="hljs-title">gt</span>; </span>{
    <span class="hljs-meta">@Insert</span>
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">insert</span><span class="hljs-params">(obj: <span class="hljs-type">T</span>)</span></span>
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Dao</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AbstractUserDao</span> : <span class="hljs-type">BaseDao&amp;lt;User&amp;gt;</span></span>() {
    <span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM users"</span>)</span>
    <span class="hljs-keyword">abstract</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUsers</span><span class="hljs-params">()</span></span>: List&amp;lt;User&amp;gt;
}
</code></pre>
<p>Usage:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> users = abstractUserDao.getUsers()

   abstractUserDao.delete(users.first())
   abstractUserDao.insert( <span class="hljs-comment">/* some user */</span> )
</code></pre>
<h2 id="heading-observable-queries"><strong>Observable queries</strong></h2>
<p>Why would we need any observable queries?</p>
<p>The simplest and the most obvious answer is that we want our UI to update automatically when the data changes. To achieve this we can simply use <strong>LiveData</strong> or <strong>RxJava2</strong> as returning value of our query methods. The Room is generating all necessary code to update the values when a database changed.</p>
<h2 id="heading-livedata"><strong>LiveData</strong></h2>
<p>We need to add some dependencies to use the LiveData and AndroidViewModel. It’s better to use LiveData with lifecycle aware component.</p>
<pre><code class="lang-kotlin">dependencies {
  def lifecycle_version = <span class="hljs-string">"1.1.1"</span>
  <span class="hljs-comment">//…</span>
  implementation <span class="hljs-string">"android.arch.lifecycle:extensions:<span class="hljs-variable">$lifecycle_version</span>”
  kapt "</span>android.arch.lifecycle:compiler:$lifecycle_version<span class="hljs-string">"
  //…
}</span>
</code></pre>
<p>Now we need to modify the method for getting the user by <strong>Id</strong>.</p>
<pre><code class="lang-sql">@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = :userId<span class="hljs-string">")
fun user(userId: Long): LiveData&amp;lt;User&amp;gt;</span>
</code></pre>
<p>To get all benefits of the architecture components we need to create a separate activity with the corresponding <strong>AndroidViewModel</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LiveDataViewModel</span></span>(application: Application) : AndroidViewModel(application) {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> userDao: UserDao = Injector.provideUserDao(application)

    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getUser</span><span class="hljs-params">(userId: <span class="hljs-type">Long</span>)</span></span>: LiveData&amp;lt;User&amp;gt; {
        <span class="hljs-keyword">return</span> userDao.user(userId)
    }
}
</code></pre>
<p>And the activity where in order to observe database for changes, we need to register an observer on the <strong>LiveData</strong> object by using the method <strong><em>observe()</em></strong> as shown below:</p>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LiveDataTestActivity</span> : <span class="hljs-type">AppCompatActivity</span></span>() {

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> {
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live_data_test)

        <span class="hljs-keyword">val</span> model = ViewModelProviders.of(<span class="hljs-keyword">this</span>).<span class="hljs-keyword">get</span>(LiveDataViewModel::<span class="hljs-keyword">class</span>.java)
        model.getUser(<span class="hljs-number">1</span>).observe(<span class="hljs-keyword">this</span>, Observer { user -&amp;gt;
            Timber.i(<span class="hljs-string">"<span class="hljs-variable">$user</span>"</span>)
        })
    }
}
</code></pre>
<p>That’s all! Now when we run the <strong>LiveDataTestActivity</strong> we will see a similar log output:</p>
<pre><code class="lang-kotlin">User(
   id=<span class="hljs-number">1</span>, 
   firstName=John, 
   lastName=Doe, 
   fullName=John Doe, 
   birthday=<span class="hljs-number">1980</span>-<span class="hljs-number">01</span>-<span class="hljs-number">01</span>, 
   homeAddress=Address(
                  street=Washington Street, 
                  city=Arkansas, 
                  postal=<span class="hljs-number">72701</span>), 
   officeAddress=Address(
                  street=<span class="hljs-number">4</span>th Street, 
                  city=Arkansas, 
                  postal=<span class="hljs-number">72749</span>), 
   emailAddress=<span class="hljs-symbol">jdoe@</span>mail.com, 
   phoneNumber=<span class="hljs-number">001333444555</span>, 
   picture=/pictures/jdoe/avatar/s34trag_732_jkdal.png, 
   status=ACTIVE
)
</code></pre>
<p>The timber log will be now called every time Room detects that the result of that query you wrote has changed.</p>
<h2 id="heading-rxjava2"><strong>RxJava2</strong></h2>
<p>For using <strong>RxJava2</strong> we also need some more dependencies. <strong>RxJava</strong>, <strong>RxKotlin</strong> and <strong>RxJava</strong> support for Room</p>
<pre><code class="lang-kotlin">implementation <span class="hljs-string">"io.reactivex.rxjava2:rxkotlin:2.3.0"</span>
implementation <span class="hljs-string">"io.reactivex.rxjava2:rxandroid:2.1.0"</span>
<span class="hljs-comment">//..</span>
implementation <span class="hljs-string">"android.arch.persistence.room:rxjava2:<span class="hljs-variable">$room_version</span>"</span>
</code></pre>
<p>Similarly, as in the previous case, we need to modify the query in <strong>UserDao</strong></p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Query(<span class="hljs-meta-string">"SELECT * FROM users WHERE id = :userId"</span>)</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">userRx</span><span class="hljs-params">(userId: <span class="hljs-type">Long</span>)</span></span>: Flowable&amp;lt;User&amp;gt;
</code></pre>
<p>Usage:</p>
<pre><code class="lang-kotlin">userDao.userRx(<span class="hljs-number">1</span>)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext { Timber.i(<span class="hljs-string">"<span class="hljs-variable">$it</span>"</span>) }
                .subscribe()
                .addTo(disposable)
</code></pre>
<p>Log output will be the same as in <strong>LiveData</strong>.<br />If you are using RxJava2 in your application make your database reactive too! We can use the advantage of <strong>Rx</strong> returning also types such as <strong>Maybe, Single, Flowable.</strong></p>
<h3 id="heading-flowable"><code>@Flowable</code></h3>
<ul>
<li><p>No data (no rows were returned) neither onNext or onError will be emitted</p>
</li>
<li><p>Data – onNext will be triggered</p>
</li>
<li><p>Update – every data that will be updated and is a part of a query will trigger another onNext</p>
</li>
</ul>
<pre><code class="lang-sql">@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = :userId<span class="hljs-string">")
fun userRxFlowable(userId: Long): Flowable&amp;lt;User&amp;gt;</span>
</code></pre>
<h3 id="heading-single"><code>@Single</code></h3>
<ul>
<li><p>No data (no rows were returned) onError(EmptyResultSetException) will be triggered</p>
</li>
<li><p>Data – onSucces will be triggered</p>
</li>
<li><p>Update – nothing happens</p>
</li>
</ul>
<pre><code class="lang-sql">@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = :userId<span class="hljs-string">")
fun userRxSingle(userId: Long): Single&amp;lt;User&amp;gt;</span>
</code></pre>
<h3 id="heading-maybe"><code>@Maybe</code></h3>
<ul>
<li><p>No data (no rows were returned) Maybe will complete</p>
</li>
<li><p>Data – onSuccess will be triggered and Maybe will complete</p>
</li>
<li><p>Update – nothing happens</p>
</li>
</ul>
<pre><code class="lang-sql">@Query("<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = :userId<span class="hljs-string">")
fun userRxMaybe(userId: Long): Maybe&amp;lt;User&amp;gt;</span>
</code></pre>
<p>**Watch out!<br />**You need to be aware that every update on the field used in DB query will trigger the observable query and UI will be updated (or deleted) – this is OK if you design your app like that, but it can be also – unwanted behaviour. You should control your code. When you don’t need to update your UI try to use Single instead of Flowable. Make sure to handle the emission in your DAO.</p>
<p>With flowable you can simply use <code>.distinctUntilChanged()</code><a target="_blank" href="http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html#distinctUntilChanged--"><strong><em>link</em></strong></a><br />With LiveData it’s a bit harder and you can see more <a target="_blank" href="https://gist.github.com/florina-muntenescu/fea9431d0151ce0afd2f5a0b8834a6c7"><strong><em>here</em></strong></a>.</p>
<p>That’s All Folks! We’ve reached the end of the third part of the introduction to the Room Persistence Library. I hope you’ve enjoyed this post. In case of any questions don’t hesitate to write a comment.</p>
<blockquote>
<p><em>Edit: [October 8.2018]</em><br /><em>During work on this post, a new version of Room was released (2.1.0-alpha01).</em></p>
</blockquote>
<p>Cheers!</p>
<blockquote>
<p><em>This post was originally published on</em><a target="_blank" href="https://speednetsoftware.com/room-persistence-library-introduction-part-3/"><strong><em>Speednet blog</em></strong></a><em>on 16.10.2018</em></p>
</blockquote>
]]></content:encoded></item></channel></rss>