<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohitsoni on Medium]]></title>
        <description><![CDATA[Stories by Mohitsoni on Medium]]></description>
        <link>https://medium.com/@mohitsoni48?source=rss-cc53cf151c1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cKUZ_6AdsBzq38G33Fs9TA.jpeg</url>
            <title>Stories by Mohitsoni on Medium</title>
            <link>https://medium.com/@mohitsoni48?source=rss-cc53cf151c1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:26:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohitsoni48/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Auto-Tune Your llama.cpp GPU Config Instead of Guessing the Flags]]></title>
            <link>https://medium.com/@mohitsoni48/auto-tune-your-llama-cpp-gpu-config-instead-of-guessing-the-flags-bcccb4d2f452?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcccb4d2f452</guid>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 15:55:25 GMT</pubDate>
            <atom:updated>2026-07-02T15:55:25.379Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The difference between 20 tokens a second and 80 on the exact same GPU is usually a dozen flags nobody tells you about. TurboLLM benchmarks your hardware and sets them for you.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUsJzGTTh8eVBUOgQdaHBQ.png" /></figure><p>Set GPU layers a little too high and llama.cpp quietly spills into system RAM. No crash, no error in the log, your speed just collapses from 40 tokens a second to 4. Finding the real ceiling by hand, for every model and every quant you try, gets old fast, so TurboLLM’s auto-tune does it for you in one benchmark run.</p><h3>What it actually tunes</h3><p><strong>GPU layers.</strong> It reads real VRAM off your GPU and offloads as many layers as it can while leaving about 1GB of headroom, enough that a stray browser tab grabbing VRAM can’t tip you into a spill mid-session.</p><p><strong>MoE expert offload.</strong> For mixture-of-experts models it balances GPU layers against CPU-resident experts. A Qwen3.6-35B-A3B on a 16GB card landed at 99 GPU layers, 20 experts kept on CPU, 42.5 tokens/sec at 200K context, measured on the machine it ran on.</p><p><strong>KV cache quant.</strong> It picks the KV cache type that actually fits your target context in whatever VRAM is left over, instead of you guessing whether f16 or a lower-bit cache survives at 200K tokens.</p><p><strong>Sampling.</strong> It reads the model’s Hugging Face card and pulls the author’s recommended temperature, top-k, top-p, and min-p. A lot of models want something other than the defaults everyone leaves in place, each value here is tagged “from card” so you can see exactly where it came from.</p><h3>Where the number comes from</h3><p>Before you even download a model, TurboLLM shows an estimated tokens/sec for it on your specific GPU, based on prior runs on similar hardware. Once you’ve loaded it and it’s benchmarked on your own machine, the number in the model list stops being an estimate, it’s measured, live, from actual generation while you chat.</p><h3>Try it</h3><p>Load any model and hit auto-tune once. (Disclosure: I built TurboLLM.) npx turbollm to start, source-available, repo at github.com/mohitsoni48/TurboLLM.</p><p>If you’ve ever watched your tokens-per-second collapse for no obvious reason, this alone is worth one run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcccb4d2f452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TurboLLM: your local model can now render UIs, not just describe them]]></title>
            <link>https://medium.com/@mohitsoni48/turbollm-your-local-model-can-now-render-uis-not-just-describe-them-47906175ab42?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/47906175ab42</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 06:30:13 GMT</pubDate>
            <atom:updated>2026-06-28T06:30:13.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uN8Cnd2rK5J-hXYxUYuMmQ.png" /></figure><p>One of my favorite things about Claude is that it doesn’t stop at text. Ask it for a dashboard and you get a dashboard. Ask for a chart and you get a chart. Ask for a landing page and it renders the actual page, right inside the chat.</p><p>Local models have been able to generate that same code for a long time. What they never had was the runtime to show it.</p><p>That’s what TurboLLM adds: artifact rendering for local models. Charts, diagrams, dashboards, full web UIs, they now render directly inside the conversation instead of dumping out as a wall of code you have to copy into a separate file just to see what it built.</p><h3>From code block to rendered page</h3><p>Here’s the difference in practice. You ask a local model to design something, and instead of staring at three hundred lines of JSX wondering what it actually looks like, you just look at it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BQVyY2f_Zqxkf0zJ8VyqA.png" /></figure><p>Open WebUI has a version of artifact rendering, but it’s a manual, side-panel affair, you get a code block, and you decide to open a viewer to see it. In TurboLLM, the model decides when to render on its own, and it shows up inline in the same message thread. No extra click, no separate pane to remember to check. It’s a small difference on paper, but it’s the difference that makes it feel like the Claude flow instead of a code preview bolted onto a chat window.</p><h3>What it looked like on my machine</h3><p>The screenshot below is not a mockup. It’s a single prompt, answered by Qwen 3.6 35B A3B, running entirely locally on an RTX 5070 Ti:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjoOpbzQFmCGI4dk07YyRg.png" /></figure><p>Dark theme, gradient call-to-action, bento-grid feature cards, all generated, then rendered, without ever leaving the chat. No copy-pasting into a sandbox site, no spinning up a dev server to check the output. The model wrote it, and TurboLLM showed it.</p><h3>Local, and actually local</h3><p>The part I care about most isn’t the visual polish, it’s where the code runs. Every artifact executes inside a sandbox with no network access. Nothing it renders can phone out, fetch a resource, or leak a prompt. The same offline-first guarantee that applies to your chats now applies to everything they produce.</p><p>If you’re running local models specifically because you don’t want your prompts or your data touching someone else’s server, an artifact preview that quietly opened a network connection would defeat the point. This one doesn’t.</p><h3>Try it</h3><blockquote>npx turbollm</blockquote><p>Load a model that’s reasonably capable at code (Qwen3.6, recent Llama, or similar), ask it to build something visual, and watch it render instead of just describing what it would look like.</p><p>If you’ve been holding off on local models because they felt like a step down from what hosted tools can show you, this closes a good chunk of that gap.</p><p>TurboLLM is open source. Star it, file an issue, or send a PR: github.com/mohitsoni48/TurboLLM</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47906175ab42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TurboLLM: a local LLM app that tunes itself to your GPU]]></title>
            <link>https://medium.com/@mohitsoni48/turbollm-a-local-llm-app-that-tunes-itself-to-your-gpu-fb94a8c1ffb1?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb94a8c1ffb1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 06:02:23 GMT</pubDate>
            <atom:updated>2026-06-27T06:02:23.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4XJw9n7CLmBFeZgBuqZkw.png" /></figure><p>Local LLMs have gotten genuinely good. The tools for running them haven’t kept up.</p><p>LM Studio and Ollama get you chatting in two minutes. The trouble starts right after, the moment you push a local model the way you’d push a cloud one.</p><p>You tune GPU layers by hand and never quite trust the number. You ask about something recent and the model invents an answer. You ask for a chart and get a wall of HTML. You wire it into Claude Code and end up building a gateway.</p><p>I got tired of every piece being its own weekend project, so I built TurboLLM: one app that does all of it. `npx turbollm`, no install, runs on Windows, macOS, and Linux.</p><p>Here’s what it does, starting with the part I use every day.</p><h3>Auto-tune: stop hand-tuning GPU layers, KV cache, and sampling</h3><p>Set GPU layers a little too high and llama.cpp quietly spills into system RAM. No crash, no log, your speed just collapses from 40 tokens a second to 4 and the model looks like it’s having a bad day. Finding the real ceiling by hand, for every model and every quant, gets old fast.</p><p>Auto-tune does it for you in one run, and sets four things:</p><h4>GPU layers.</h4><p>It reads real VRAM off the GPU and offloads as many layers as it can while leaving about 1GB of headroom, enough that a stray browser tab can’t tip you into a spill.</p><h4>MoE expert offload.</h4><p>For MoE models it balances GPU layers against CPU experts. A Qwen3 35B A3B on a 16GB card landed at 99 layers, 20 experts on CPU, 42.5 tok/s at 200k context. A dense Qwen3.5 9B on the same card hit 94.6 tok/s.</p><h4>KV cache quant.</h4><p>It picks the KV cache quant that fits your target context in whatever VRAM is left, instead of you guessing whether f16 or q8 survives at 200k tokens.</p><h4>Sampling.</h4><p>It reads the model’s Hugging Face card and pulls the author’s recommended temperature, top-k, top-p, and min-p. Qwen3 wants temperature 0.6; most people run it at 1.0 and blame the model. Each value is tagged “from card” so you can see where it came from.</p><p>It all saves to the model’s profile, so the next load is already tuned. This is the single biggest reason to use the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTjSAJDvcBXiyIEKco_4HQ.png" /></figure><h3>Run any engine: llama.cpp, vLLM, MLX, and more in one app</h3><p>llama.cpp, vLLM, MLX, TurboQuant, llamafile, KoboldCpp. Each one normally means its own install, its own flags, its own model format. TurboLLM runs all of them from one screen.</p><p>It reads your hardware and only offers what actually fits: on a Windows CUDA box it recommends llama.cpp and TurboQuant and greys out MLX with a reason; on a Mac it surfaces MLX. It can even build llama.cpp for you, download the CUDA toolkit if you don’t have one, and rebuild when upstream moves ahead. Running any llama.cpp fork, auto-tuned to your GPU, without compiling it yourself, is the part I haven’t seen anywhere else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egnvDuKkzmEcjyhoQJiUWw.png" /></figure><h3>Research mode: give your local model real web search</h3><p>Local models are confidently wrong about anything recent. Ask which coding model is best right now and you’ll get something from a year ago, or a name it made up.</p><p>Research mode makes the model search the web before it answers. Telling it to search in the system prompt doesn’t work; it ignores you about half the time. Forcing it at the tool level does: it can’t reply until it’s run a few searches. It then checks each sentence against the sources and badges them in the chat, so you can see what’s grounded and what isn’t. Search runs through Tavily, Kagi, or a self-hosted SearXNG, and only the query ever leaves your machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTt-lNTR_zg4CTGX0WwU4g.png" /></figure><h3>Artifacts: Claude-style inline rendering for local models</h3><p>Local models could always write the code for a chart or a dashboard. What was missing was somewhere to actually run it, instead of leaving a wall of HTML in the chat.</p><p>TurboLLM renders it inline. When the output is a webpage, an SVG, or a diagram, it shows up live in the conversation in a sandboxed frame with no network access. Ask for a dashboard, get a dashboard, the way it works with Claude. Open WebUI does this in a side panel you open by hand; here it’s automatic. Export to PNG, SVG, or GIF is fully offline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMLhh88Zl-5osB7T_D0YTw.png" /></figure><h3>Background agents: long-running local AI tasks</h3><p>Kick off a long task, like turning a stack of docs into a summary or a twenty-minute research run, then close the tab and walk away. The daemon keeps going and saves progress as it works, so a dropped connection or a shut laptop doesn’t lose anything. That’s what local models need to compete with cloud agents on long jobs, where one network blip would otherwise cost you the whole run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsnVz5vczzjSVOqbD0fYgg.png" /></figure><h3>A local OpenAI-compatible gateway for Claude Code</h3><p>TurboLLM runs a local OpenAI- and Anthropic-compatible gateway, so your local model can stand in for the cloud.</p><h4>Point any client at it.</h4><p>Claude Code, Continue, anything OpenAI-compatible.</p><h4>Auto-swap.</h4><p>Ask for a model that isn’t loaded and it loads it, keeping up to four hot at once.</p><h4>MCP host.</h4><p>Add MCP servers once and their tools show up in the app and through the gateway.</p><h4>`turbollm launch claude`.</h4><p>Opens Claude Code already wired up, with timeouts tuned for local speeds so it doesn’t fire retries while your model is still thinking.</p><h3>Is TurboLLM a good LM Studio or Ollama alternative?</h3><p>If you just want to chat with a model, LM Studio and Ollama do that well, so keep using them. TurboLLM is the alternative for when you’ve hit their ceiling. Here’s where it differs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26XX4ZuO-c5zcQiYZA2dzg.png" /></figure><p>And the auto-tuning shows up as speed. Same GPU (RTX 5070 Ti, 16GB), same model, same 200K context, measured generation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNSYrlDPibDWOzTY_vOXTQ.png" /></figure><p>That’s TurboLLM ahead on the exact same llama.cpp. Swap in the TurboQuant fork, a low-bit KV cache LM Studio can’t even load, and on a large-KV 27B model at matched quality it hits 24.6 t/s against LM Studio’s 11.4, more than 2x faster, with 1.7x quicker prefill.</p><p>So it’s for you if:</p><p>- you’re tired of hand-tuning every model and never trusting the number<br>- you want answers backed by real web search, not confident guesses<br>- you want charts and UIs to render, not arrive as code<br>- you’re using local models for agents or as a Claude Code backend</p><p>One app, tuned to your hardware. Repo’s at github.com/mohitsoni48/TurboLLM.</p><p>If you’ve ever watched your tokens-per-second collapse for no reason, auto-tune alone is worth one run.</p><p>Works on Windows / macOS / Linux.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb94a8c1ffb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Persistent State in Jetpack Compose]]></title>
            <link>https://proandroiddev.com/managing-persistent-state-in-jetpack-compose-55ffc1ec6ea4?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ffc1ec6ea4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 05:51:46 GMT</pubDate>
            <atom:updated>2025-03-01T12:35:45.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQKE1-CTcZphpLGOpD5new.jpeg" /></figure><p>State management in Jetpack Compose becomes challenging when dealing with persistent data. Traditionally, developers rely on Android’s DataStore, but integrating it seamlessly with Compose can require excessive boilerplate. Let’s explore how to simplify this by building our own <strong>PreferenceState</strong> class to read and write data to dataStore just as you would read and update data from a state.</p><p>If you want to skip the implementation, you can check out the <strong>PreferenceState</strong> library that I developed. It provides the same functionality without the need to write boilerplate code. You can find it here: <a href="https://github.com/mohitsoni48/PreferenceState">PreferenceState Library</a>, or continue reading to understand how it works step by step.</p><h3>Problem Statement</h3><p>When you need to store data in DataStore and update the UI state based on it, the typical approach involves multiple layers: a ViewModel, a repository, and then collecting DataStore values to update the state. This results in excessive boilerplate code, making the implementation unnecessarily complex.</p><h3>How We Solve This Problem</h3><p>To simplify state persistence in Jetpack Compose, we will create a PreferenceState class that directly interacts with DataStore while behaving like a MutableState. This eliminates the need for a ViewModel or repository, reducing boilerplate code while keeping the logic concise and reusable.</p><h3>Step-by-Step Implementation of PreferenceState</h3><h4>Step 1: Creating the PreferenceState Class</h4><pre>abstract class PreferenceState&lt;T&gt;(<br>    private val key: Preferences.Key&lt;T&gt;,<br>    private val defaultValue: T,<br>    private val dataStore: DataStore&lt;Preferences&gt;<br>) : MutableState&lt;T&gt; {<br>    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())<br><br>    private val _state = mutableStateOf(defaultValue)<br><br>    override var value: T<br>        get() = _state.value<br>        set(value) {<br>            _state.value = value<br>            scope.launch {<br>                dataStore.edit { it[key] = value }<br>            }<br>        }<br><br>    init {<br>        scope.launch {<br>            dataStore.data.map { it[key] ?: defaultValue }<br>                .collect { newValue -&gt;<br>                    withContext(Dispatchers.Main) {<br>                        _state.value = newValue<br>                    }<br>                }<br>        }<br>    }<br><br>    override fun component1(): T = value<br>    override fun component2(): (T) -&gt; Unit = { value = it }<br>}</pre><h4>Step 2: Creating a Custom Preference State Class</h4><pre>class UsernamePreferenceState: PreferenceState&lt;String&gt;(<br>    key = stringPreferencesKey(&quot;username&quot;),<br>    defaultValue = &quot;Guest&quot;,<br>    dataStore = createDataStore()<br>)</pre><p>Since creating a DataStore instance is straightforward, we are skipping that part.</p><h4>Step 3: Creating a Remember Function for Compose</h4><pre>@Composable<br>fun rememberUsernamePreferenceState(): MarketViewSwitchState = remember {<br>    UsernamePreferenceState()<br>}</pre><h3>Using PreferenceState in a Real-Life Scenario</h3><p>Let’s say we want to persist a <strong>username</strong> input field across app restarts. We can use PreferenceState like this:</p><pre>@Composable<br>fun UserProfileScreen(modifier: Modifier = Modifier) {<br>    var username by rememberUsernamePreferenceState()<br><br>    Column {<br>        TextField(<br>            value = username,<br>            onValueChange = { username = it },<br>            label = { Text(&quot;Username&quot;) }<br>        )<br>    }<br>}</pre><p>This allows username to persist even when the app is restarted, without manually handling Flow collections or LaunchedEffect calls.</p><h3>Conclusion</h3><p>Building a PreferenceState class from scratch helps in understanding how DataStore integrates with Compose. However, for convenience, the <strong>PreferenceState</strong> library provides a ready-to-use implementation, making persistent state management easier in Jetpack Compose applications. You can find the library here: <a href="https://github.com/mohitsoni48/PreferenceState">PreferenceState Library</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ffc1ec6ea4" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/managing-persistent-state-in-jetpack-compose-55ffc1ec6ea4">Managing Persistent State in Jetpack Compose</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Garbage Collector in KMP — Part 2]]></title>
            <link>https://proandroiddev.com/garbage-collector-in-kmp-part-2-b0577668ea16?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0577668ea16</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 14:56:10 GMT</pubDate>
            <atom:updated>2024-09-16T08:27:29.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>Garbage Collector in KMP — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ld0aEHQkvp5aGKHVoYxUg.png" /></figure><p>This article is the second part of my series on how the garbage collector (GC) functions in Kotlin Multiplatform (KMP). If you haven’t yet, I recommend starting with <a href="https://medium.com/proandroiddev/garbage-collector-in-kmp-part-1-305dc345700d">Part 1</a> to build a solid foundation.</p><p>Now that you have a grasp of how the GC works in Android apps built with KMP, it’s time to delve into a more intricate aspect: Kotlin’s GC implementation in iOS.</p><p>However, before jumping into how KMP’s GC operates on iOS, it’s crucial to understand how garbage collection works in native iOS apps written in Swift or Objective-C. While this may be second nature to iOS developers, it’s valuable knowledge for Android developers stepping into the iOS world — after all, “to know the road ahead, ask those coming back.”</p><h3>Understanding Garbage Collection in iOS: Swift</h3><p>In Swift, memory management is handled differently compared to other languages like Java or Kotlin. Swift doesn’t use a traditional garbage collector. Instead, it relies on a system called <strong>Automatic Reference Counting (ARC)</strong>. This method ensures efficient memory usage while providing a seamless experience for developers.</p><h4>How ARC Works</h4><p>In ARC, every time you create an instance of a class, Swift automatically tracks how many references are pointing to it. Each time a new reference is created, the count increases, and when a reference is removed, the count decreases. As soon as the reference count reaches zero, Swift deallocates the memory, effectively cleaning up unused instances.</p><p>This differs from a traditional garbage collector, which periodically checks for unused objects in memory and clears them. With ARC, deallocation happens immediately when an object is no longer needed, making memory management predictable.</p><h4>Reference Cycles and Weak References</h4><p>One challenge with ARC is the possibility of <strong>strong reference cycles</strong>, where two objects hold strong references to each other, preventing memory deallocation. To solve this, Swift provides <strong>weak</strong> and <strong>unowned</strong> references. A weak reference doesn’t increase the reference count and can be set to nil once the object it points to is deallocated. An unowned reference, on the other hand, assumes that the object it refers to will always exist for the lifetime of the reference.</p><h4>ARC in Action</h4><p>Swift’s ARC handles memory automatically for most scenarios, reducing the need for developers to manually manage memory. However, understanding how ARC works can help in optimizing memory usage and preventing issues like memory leaks.</p><p>You should definitely learn more about this in detail and there are lot of articles available on this so I won’t dive further.</p><h3>Understanding Garbage Collection in iOS: Kotlin</h3><p>The garbage collection (GC) in iOS apps operates through a combination of <strong>Kotlin Native’s GC </strong>and <strong>Automatic Reference Counting (ARC)</strong>. This leads to a key difference depending on your development approach: whether you’re building the UI in SwiftUI while sharing business logic in Kotlin, or you’re also sharing the UI layer using Compose Multiplatform. Let’s dive into both scenarios to understand how they work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af1FLAkwCdycSuI-rERTxg.jpeg" /></figure><h4>Shared Business Logic in Kotlin, UI in SwiftUI: How ARC and Kotlin Native GC Coexist</h4><p>When building an iOS app with Kotlin Multiplatform, a common pattern is to share business logic in Kotlin while creating the UI in SwiftUI. This introduces an interaction between two memory management systems: iOS’s ARC (Automatic Reference Counting) and Kotlin Native’s garbage collector.</p><ul><li><strong>Object Management</strong>: When Kotlin objects are passed from the shared Kotlin code to SwiftUI, they are wrapped in a DisposableHandle. ARC takes over from here and manages the lifecycle of these wrapped objects on the Swift side. Each time the object is referenced, ARC increments its reference count, and when it’s no longer needed, ARC decrements the count. Once the count hits zero, the object is deallocated.</li><li><strong>Reference Tracking by Kotlin Native GC</strong>: Even though ARC manages these Kotlin objects on the Swift side, Kotlin Native’s garbage collector is still involved because the actual memory allocation and lifecycle of the Kotlin object remain under the control of Kotlin Native. Kotlin Native’s garbage collector tracks references internally and ensures that objects in circular references or other complex scenarios are properly deallocated.</li><li><strong>Passing Swift Objects to Kotlin</strong>: The reverse situation is also possible: when Swift objects are passed to the Kotlin code, ARC continues to manage them. Kotlin Native, on the other hand, keeps track of these references on the Kotlin side. This ensures that even when objects cross language boundaries, neither ARC nor Kotlin Native deallocates them prematurely.</li><li><strong>Memory Overhead</strong>: While this approach works well in many cases, there’s an overhead when objects need to be wrapped or unwrapped to transition between SwiftUI and Kotlin Native. Every time an object is transferred across the boundary, there is an additional layer of wrapping that could introduce performance costs, particularly when complex or frequent object transfers are involved.</li></ul><h4>Extending UI Sharing with Compose Multiplatform</h4><p>Instead of keeping the UI in SwiftUI, another option is to share the UI code using <strong>Compose Multiplatform</strong>. This approach allows you to create the UI in Kotlin and share it across platforms, meaning the entire app (business logic and UI) runs on Kotlin. In this case, memory management shifts almost entirely to Kotlin Native’s garbage collector, with little interaction with ARC.</p><ul><li><strong>UI Rendering in Kotlin Native</strong>: Compose Multiplatform relies entirely on Kotlin’s memory management system. Because the UI code is now in Kotlin, ARC doesn’t play a role in managing the UI components. Kotlin Native’s garbage collector becomes responsible for managing all objects, including UI components, which would have been handled by ARC if SwiftUI were used.</li><li><strong>Performance Considerations</strong>: Kotlin Native’s garbage collection is efficient but isn’t optimized for high-demand tasks like rendering complex or dynamic UI components. SwiftUI benefits from ARC’s fast, immediate deallocation of unused objects. However, in Kotlin Native, garbage collection cycles are less predictable and might introduce temporary memory spikes if not handled carefully.</li><li>In essence, while Compose Multiplatform simplifies the codebase by unifying the UI layer, the cost is less control over memory deallocation and potentially slower cleanup of UI components compared to SwiftUI with ARC.</li><li><strong>Resource Management in UI</strong>: Since Kotlin Native doesn’t free up objects as quickly as ARC, using Compose Multiplatform for UI might result in larger memory footprints, especially when dealing with animations or high-frequency UI updates. This can affect the performance of your app in terms of responsiveness and memory usage, particularly in scenarios involving dynamic UIs.</li></ul><h3>Potential Pitfalls and Performance Considerations</h3><ol><li><strong>Retain Cycles</strong>: ARC struggles with circular references (or retain cycles), where two objects hold strong references to each other and neither can be deallocated. Kotlin Native GC, on the other hand, can detect and clean up circular references during garbage collection. However, if retain cycles occur at the boundary between Kotlin Native and Swift, managing these cycles becomes more complicated. You may need to manually intervene by using weak references in Swift or by ensuring proper nullability and lifecycle management in Kotlin.</li><li><strong>GC Delays</strong>: One of the major performance differences between ARC and Kotlin Native GC is how they handle memory deallocation. ARC deallocates objects as soon as the reference count hits zero. This is beneficial for performance-critical areas like UI rendering because memory is freed up promptly. Conversely, Kotlin Native’s garbage collector runs on a separate cycle. This means that even if objects are no longer in use, they may not be deallocated immediately, potentially causing memory bloat in situations that demand real-time memory management.</li><li><strong>Object Transfer Overhead</strong>: The overhead of transferring objects between Kotlin and Swift can lead to performance bottlenecks, especially when the app has frequent interactions between the UI and business logic layers. This becomes more noticeable in scenarios where large or complex objects are passed between Kotlin and Swift repeatedly, as both ARC and Kotlin Native need to wrap and unwrap these objects.</li><li><strong>UI Complexity with Compose Multiplatform</strong>: When sharing the UI with Compose Multiplatform, you rely entirely on Kotlin Native’s garbage collection. This can introduce memory management inefficiencies compared to SwiftUI, especially for apps with complex UI hierarchies or heavy animations. Compose is not yet as optimized for iOS as SwiftUI, which could result in slower performance in UI-heavy applications.</li></ol><h3>Best Practices for Efficient Memory Management in KMP Projects</h3><ol><li><strong>Careful Object Lifecycle Management</strong>: In cases where objects cross the Kotlin-Swift boundary, it’s crucial to monitor how they are referenced. Both Swift and Kotlin developers should be aware of how strong references are managed and where potential retain cycles might form. Using weak references or explicitly nullifying references on the Kotlin side can help mitigate memory leaks or unnecessary memory retention.</li><li><strong>Optimize Cross-Language Calls</strong>: To minimize the overhead caused by frequent object transfers between Kotlin and Swift, optimize how often objects need to cross the language boundary. Each time you pass an object from Kotlin Native to Swift (or vice versa), the system incurs the cost of wrapping and unwrapping objects. Reducing the number of cross-language calls by grouping operations together, batching data transfers, or simplifying the interface between Kotlin and Swift can improve performance. For example, instead of calling Kotlin business logic repeatedly from Swift for small operations, consider aggregating tasks on the Kotlin side, returning the result once all calculations are complete. This reduces the interaction frequency between Kotlin GC and ARC, thereby lowering the performance overhead.</li><li><strong>Reduce Object Creation in UI Rendering</strong>: When using Compose Multiplatform, be mindful of how often objects are created, particularly within UI rendering loops. Excessive object creation can lead to high memory churn and put pressure on the Kotlin Native GC, which may not deallocate memory as quickly as ARC. Reuse objects wherever possible and structure your code to minimize unnecessary object instantiation, especially for short-lived UI components.</li><li><strong>Understand SwiftUI vs. Compose Memory Characteristics</strong>: SwiftUI with ARC offers instantaneous memory deallocation, whereas Compose relies on Kotlin Native’s GC, which might introduce delays. If your app is UI-heavy and performance-critical (e.g., animation or real-time data), SwiftUI’s ARC will likely provide better memory performance. On the other hand, Compose Multiplatform simplifies code sharing but requires extra attention to memory usage and efficient UI rendering.</li><li><strong>Manual Garbage Collection Control in Kotlin Native</strong>: Although Kotlin Native manages memory automatically, there are ways to exert more control when necessary. Kotlin Native provides mechanisms for manually triggering garbage collection through the GC.collect() function. This can be helpful in memory-sensitive areas where you want to ensure that unused objects are deallocated promptly.</li><li><strong>Monitor Memory Usage with Tools</strong>: Memory management issues, such as leaks, retain cycles, or excessive garbage collection delays, can be hard to catch without proper tools. Regularly profile your app’s memory behavior using tools like Xcode Instruments (for Swift/ARC) and built-in memory profilers. Identifying memory leaks, redundant allocations, or unexpected memory growth early will help you tune your app for optimal performance.</li><li><strong>Balance Between Shared and Native UI</strong>: If memory management performance becomes a bottleneck, consider whether you need to share the UI via Compose Multiplatform or if it makes more sense to use SwiftUI for the UI and share only the business logic. Native UIs will always be more efficient in managing platform-specific resources. For projects where UI performance is critical, sticking to SwiftUI while sharing Kotlin business logic can provide the best memory performance.</li></ol><h3>Conclusion</h3><p>When building iOS apps using Kotlin Multiplatform, understanding how ARC and Kotlin Native’s garbage collector interact is key to optimizing performance and ensuring smooth memory management. Sharing business logic from Kotlin while building the UI in SwiftUI ensures native performance benefits but comes with some GC overhead. On the other hand, sharing the UI via Compose Multiplatform can simplify development but may introduce memory management challenges unique to Kotlin Native’s garbage collection system.</p><p>Ultimately, the choice between SwiftUI and Compose Multiplatform for your UI layer should balance memory management efficiency with code maintainability, based on your project’s requirements. Both approaches have their pros and cons, and understanding how ARC and Kotlin Native GC work together will help you make informed decisions as you navigate the complexities of Kotlin Multiplatform development.</p><h3>Bonus</h3><p>I’m sure you might have plenty of questions about GC after reading this, and I’m here to help. If there’s enough interest, I’ll create a demo app to showcase the GC in action across different scenarios: an Android app in Kotlin, an iOS app with SwiftUI, and an iOS app using Compose Multiplatform. The demo will compare performance, memory overhead, and GC behavior. Let me know in the comments if you’d like to see it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0577668ea16" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/garbage-collector-in-kmp-part-2-b0577668ea16">Garbage Collector in KMP — Part 2</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Garbage Collector in KMP — Part 1]]></title>
            <link>https://proandroiddev.com/garbage-collector-in-kmp-part-1-305dc345700d?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/305dc345700d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 16:57:52 GMT</pubDate>
            <atom:updated>2024-09-12T18:44:34.323Z</atom:updated>
            <content:encoded><![CDATA[<h3>Garbage Collector in KMP — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbNA0nFDu_-MVEna3cH4Jw.png" /></figure><p>Kotlin Multiplatform (KMP) is quickly gaining traction, with many large organizations adopting it for app development. However, for any app to run smoothly, it’s crucial to understand how it utilizes device resources. Neglecting to optimize this can lead to poor user experiences — crashes, lag, or even the operating system terminating the app when it runs in the background. If you’re considering using KMP in a production app, it’s essential to grasp how memory management works in a KMP environment.</p><p>This article is the first of a two-part series, where you’ll dive into the finer details of the Garbage Collector (GC) and its role in optimizing performance.</p><h3>Basics</h3><p>A Garbage Collector (GC) is a system used in many programming languages to automatically manage memory. It identifies and releases memory that’s no longer needed by a program, preventing memory leaks and improving performance. The GC monitors objects in memory, and when an object is no longer accessible or referenced, it deallocates that memory, making it available for other processes. This automation helps developers avoid the pitfalls of manual memory management, which can often be complex and error-prone.</p><p>While GC is a common feature in almost all programming languages, the way it operates can differ from one language to another. Now, for new developers, it’s worth noting that you don’t necessarily have to manually invoke the GC (though you can if you wish). Instead, it’s typically triggered by the language’s runtime environment, not by the operating system itself. This highlights a key point — GC behavior is language-triggered, not OS-triggered. So, it becomes crucial to understand how the GC works within the specific language you’re using.</p><p>This understanding becomes even more significant in cross-platform languages like Kotlin, where the garbage collection method varies between iOS and Android. In essence, GC is not only language-specific but also platform-specific.</p><p>In this part, we’ll primarily focus on the workings of the GC in Android, as it’s the core platform for Kotlin.</p><h3>Understanding the Working of the Garbage Collector in Kotlin for Android</h3><p>Since Kotlin is fully interoperable with Java, it inherits its memory management system from Android’s runtime environment. Unlike traditional JVM environments, Android uses the Android Runtime (ART), which employs its own garbage collection strategies tailored specifically for mobile applications.</p><h4>ART and the Dalvik Garbage Collector</h4><p>Android used to rely on the Dalvik Virtual Machine (DVM) before transitioning to ART in Android 5.0 (Lollipop). ART is designed to improve overall performance by employing more efficient garbage collection methods.</p><p>The ART garbage collector is optimized for mobile constraints such as limited CPU, memory, and battery. Some of the main garbage collection strategies used in ART include:</p><ul><li><strong>Partial GC</strong>: Collects garbage from only the young generation (newer objects), which is usually faster and less disruptive to the user experience.</li><li><strong>Full GC</strong>: A more comprehensive garbage collection cycle that reclaims memory from the entire heap, including both young and old generations.</li><li><strong>Concurrent GC</strong>: Runs garbage collection concurrently with the application, reducing pause times that might otherwise cause noticeable stutters in UI performance.</li></ul><h4>How the Garbage Collector Works</h4><ol><li><strong>Object Allocation</strong>: When an object is created, it is allocated memory in the heap. The application continues to reference this object as long as it is needed.</li><li><strong>Object Reachability</strong>: The garbage collector continuously tracks the references to objects. Objects that are still referenced by running code are considered reachable and are not eligible for garbage collection.</li><li><strong>Mark and Sweep</strong>: The GC uses a process called <strong>Mark and Sweep</strong>. During the mark phase, the garbage collector traverses all objects and marks those that are reachable. In the sweep phase, it collects all objects that are unmarked and frees the memory.</li><li><strong>Generational Garbage Collection</strong>: The heap is divided into two generations:</li></ol><ul><li><strong>Young Generation</strong>: For newly created objects.</li><li><strong>Old Generation</strong>: For long-lived objects.</li></ul><p>Most objects are short-lived and are quickly garbage-collected from the young generation. Objects that survive multiple garbage collection cycles in the young generation are moved to the old generation, where they are collected less frequently.</p><p><strong>5. Compacting Memory</strong>: Once the unused objects are removed, the garbage collector may also compact the memory by rearranging the remaining objects. This helps in avoiding memory fragmentation and ensures efficient memory allocation for future objects.</p><h4>Impact on Android Performance</h4><p>While garbage collection in Kotlin (via the JVM) is automatic, it’s essential to understand that poorly managed memory can still degrade app performance. Here are some key considerations:</p><ul><li><strong>Garbage Collection Pause</strong>: When the GC runs, it can cause a pause in the application’s execution, particularly if there are many objects to collect or the heap size is large. This can lead to jank (lag) in your Android UI if not managed properly.</li><li><strong>Memory Leaks</strong>: Even with garbage collection, memory leaks can still occur if references to unused objects are not released. A common cause is static references or long-lived objects like singletons that hold onto resources unnecessarily.</li><li><strong>Optimizing Object Creation</strong>: By minimizing unnecessary object creation, especially within tight loops or frequently called methods, you can reduce the pressure on the garbage collector. Reusing objects when possible is a good practice for reducing garbage collection overhead.</li></ul><h3>Conclusion</h3><p>I won’t delve too deeply into Android’s garbage collection in KMP, as it functions similarly to that of a native Kotlin app, and there are plenty of resources available on this topic. In the next part, I’ll explore how garbage collection works in iOS apps built using KMP. Be sure to follow me to stay updated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=305dc345700d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/garbage-collector-in-kmp-part-1-305dc345700d">Garbage Collector in KMP — Part 1</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMP Roadmap for iOS developers]]></title>
            <link>https://medium.com/@mohitsoni48/kmp-roadmap-for-ios-developers-643b72e3248f?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/643b72e3248f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 12:05:56 GMT</pubDate>
            <atom:updated>2024-09-11T03:53:22.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KV9OvQgg_5ro0YNYDK01IQ.png" /></figure><p>With the introduction of Kotlin Multiplatform (KMP), Android developers have found themselves in a fortunate position. Now, they can build both iOS and Android apps with minimal extra effort and a relatively shallow learning curve. However, iOS developers, in contrast, often find themselves in the shadows, especially when tasked only with designing the UI while relying on Kotlin classes written by their Android counterparts for business logic.</p><p>If you’re an iOS developer trying to bridge this gap by learning and understanding Kotlin, you might feel adrift in the vast sea of Android documentation. This raises a crucial question: do you need to learn everything? Should you familiarize yourself with Android basics, or focus on key Kotlin features that you’ll encounter most frequently?</p><p>In this article, I’ll provide a roadmap tailored to iOS developers, helping you grasp the essentials of Kotlin, so you too can confidently contribute to writing business logic in your KMP projects.</p><h3>IDE</h3><p>While the recommended IDE for KMP is Fleet, my personal preference remains Android Studio. Both are developed by JetBrains, the creators of Kotlin, so you can confidently choose either based on your comfort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpLmvtBzRb_C0zTmgpmwdw.png" /></figure><h3>Syntax</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JbAw5WawGtXkvQkHqd9VIg.png" /></figure><p>Kotlin’s syntax closely resembles that of modern programming languages. If you’ve worked with Java or Swift, you’ll find Kotlin easy to pick up. The differences, particularly in declaring common data types, are minimal. For example…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871f2bfefddfe021f2c8586c95a9e200/href">https://medium.com/media/871f2bfefddfe021f2c8586c95a9e200/href</a></iframe><p>and so on..</p><p>Beyond the basic syntax, it’s important to understand how to create extensions and work with higher-order functions, particularly when dealing with Lists and Maps. These are powerful features in Kotlin that you’ll frequently encounter.</p><h3>What You Should Learn</h3><h4>Declarations</h4><p>In Swift, we work with classes, structs, enums, and protocols. In Kotlin, there is a broader range of declarations. Familiarizing yourself with these should be your first step toward mastering Kotlin. To keep you from feeling overwhelmed, here’s a list of Kotlin declarations and their Swift equivalents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aee473836639a1dacd3e9918fdfc5f24/href">https://medium.com/media/aee473836639a1dacd3e9918fdfc5f24/href</a></iframe><p>Keep in mind that these are not direct translations but are used for similar purposes in their respective languages. It’s important to understand how each declaration behaves in Kotlin compared to its Swift counterpart.</p><h4>Coroutines and Suspend Functions</h4><p>Coroutines and suspend functions are essential in Kotlin, appearing frequently in Repositories, UseCases, ViewModels, DAOs, and various other classes. Think of coroutines as analogous to tasks in Swift and suspend functions as async functions. Mastering these concepts is crucial to effectively working with Kotlin.</p><p>However, understanding the scope of what to learn is equally important. Coroutines are a vast and significant part of Kotlin, and while exploring them in depth can be rewarding, it’s practical to focus on key aspects to get started.</p><p>Consider focusing on the following points:</p><ul><li>What is a coroutine, and how does it differ from a thread?</li><li>What is a suspend function?</li><li>How does a coroutine interact with a suspend function?</li><li>What are the differences between suspend and sleep?</li><li>What is the scope and lifecycle of a coroutine?</li><li>What are Dispatchers, and what are their use cases?</li></ul><p>Grasping these concepts will provide a solid foundation for using coroutines effectively.</p><h4>Flow</h4><p>Flow in Kotlin is somewhat akin to Combine in Swift. It is a key component for reactive programming and is often used in conjunction with coroutines. As with coroutines, understanding Flow is crucial for Kotlin development, but it can also be expansive. To make the most of your learning time, focus on these essential aspects:</p><ul><li><strong>Hot Flow vs. Cold Flow:</strong> Understand the difference and use cases for each.</li><li><strong>SharedFlow vs. StateFlow:</strong> Learn the distinctions between these two types and when to use each.</li><li><strong>Replay Count, Buffer Size, and Other Aspects:</strong> Familiarize yourself with these settings to manage Flow effectively.</li><li><strong>Methods for Handling Flow:</strong> Explore methods such as collect, collectLatest, first, last, and others to retrieve values from a Flow.</li></ul><p>Mastering these fundamentals will give you a strong foundation in using Flow within your Kotlin projects.</p><h4>Dependency Injection</h4><p>Dependency Injection is a common concept across programming languages. However, unlike in Swift, Android and Kotlin Multiplatform (KMP) offer various tools that significantly reduce boilerplate code, making it easier to manage dependencies. In medium to large-scale Kotlin applications, you’ll almost always find one of these tools implemented.</p><p>For KMP, the most popular and widely adopted Dependency Injection framework is <strong>Koin</strong>. It’s worth exploring how to integrate Koin into your project and understanding its core principles. Their documentation provides clear and detailed guidance on getting started.</p><h3>What You Can Skip</h3><p>If you’re learning Kotlin primarily to integrate it with SwiftUI, you can safely skip the following topics:</p><ul><li>Android Components such as Activity, Fragment, Services, and Broadcast Receivers.</li><li>Creating views in XML.</li><li>Activity Lifecycle and Fragment Lifecycle.</li><li>Permission handling.</li><li>Navigation.</li></ul><p>Essentially, any topic not covered above can be considered non-essential for your current focus. However, if you plan to also develop UI with Compose Multiplatform, you’ll need to dive into these areas and become well-versed in Android development.</p><h3>Best Resources to Learn From</h3><p>To effectively learn Kotlin and Kotlin Multiplatform (KMP), a variety of resources can help you build a solid foundation and advance your skills. Here are some of the best resources to guide your learning journey (link attached to their headings) :</p><ol><li><a href="https://kotlinlang.org/docs/home.html"><strong>Official Kotlin Documentation:</strong></a></li></ol><ul><li>The Kotlin documentation is a comprehensive resource for understanding the language’s syntax, features, and best practices.</li></ul><p><strong>2. </strong><a href="https://kotlinlang.org/docs/multiplatform.html"><strong>Kotlin Multiplatform Documentation:</strong></a></p><ul><li>Explore the Kotlin Multiplatform documentation for detailed insights into creating shared code across platforms.</li></ul><p><strong>3. Community and Forums:</strong></p><ul><li><a href="https://www.linkedin.com/company/kotlin-multiplatform/"><strong>Kotlin Multiplatform development</strong></a> — Follow KMD on linkedIn to get latest updates, posts and much more on LinkedIn.</li><li><a href="https://discuss.kotlinlang.org/"><strong>Kotlin Discussions</strong></a> — Participate in discussions and get help on the Kotlin Discussions forum.</li><li><strong>Stack Overflow</strong> — A valuable resource for troubleshooting specific issues and learning from the community.</li></ul><p><strong>4. Books:</strong></p><ul><li><em>Kotlin Programming: The Big Nerd Ranch Guide</em> by Josh Skeen and David Greenhalgh offers practical examples and in-depth coverage.</li><li><em>Kotlin in Action</em> by Dmitry Jemerov and Svetlana Isakova provides a thorough introduction and practical advice.</li></ul><p><strong>5. Online Courses and Tutorials:</strong></p><ul><li><a href="https://www.jetbrains.com/academy/"><strong>JetBrains Academy</strong></a> offers interactive Kotlin courses that cater to various skill levels.</li><li><strong>Udemy</strong> has courses like <em>Kotlin for Android Development</em> and <em>Kotlin for Beginners</em>.</li><li><strong>Coursera</strong> provides courses from top universities and institutions, such as <em>Kotlin for Java Developers</em>.</li></ul><p><strong>6. YouTube Channels:</strong></p><ul><li><a href="https://www.youtube.com/@Kotlin"><strong>KotlinConf</strong></a> — Official channel for Kotlin conference talks.</li><li><a href="https://www.youtube.com/@AndroidDevelopers"><strong>Android Developers</strong> </a>— Features videos on Kotlin and Android development.</li></ul><p>By leveraging these resources, you’ll be well-equipped to master Kotlin and KMP, enhancing your development skills and productivity.</p><p>Follow me for insights and practical tips on Kotlin and KMP.</p><p>Happy Learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643b72e3248f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KColor: A library to share color between Android and iOS in KMM]]></title>
            <link>https://medium.com/@mohitsoni48/kcolor-a-library-to-share-color-between-android-and-ios-in-kmm-aca162411dc2?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca162411dc2</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 07:42:17 GMT</pubDate>
            <atom:updated>2024-09-21T13:49:46.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tvyhq28TcQWMS06Vh1PtBg.png" /></figure><p>This article is about how to use KColor, a kotlin multiplatform library aimed to share color between android and ios.</p><p>GitRepo: <a href="https://github.com/mohitsoni48/KColor">https://github.com/mohitsoni48/KColor</a></p><h3>How to install</h3><p>In project level build.gradle</p><pre>plugins {<br>    //other plugins<br>    id(&quot;io.github.mohitsoni48.KColor&quot;) version &quot;&lt;Version&gt;&quot; apply false<br>}</pre><p>In shared module build.gradle</p><pre>plugins {<br>    //other plugins<br>    id(&quot;io.github.mohitsoni48.KColor&quot;)<br>}<br><br>kotlin {<br><br>    sourceSets.commonMain {<br>        kotlin.srcDir(&quot;build/generated/colors&quot;)<br>    }<br><br>    sourceSets {<br>        commonMain.dependencies {<br>            //...<br>        }<br>    }<br>}<br><br>kColor {<br>    packageName = &quot;com.mohitsoni.kcolorsample&quot;<br>    sharedModule = &quot;shared&quot; //optional, default is shared<br>    iosAppName = &quot;iosApp&quot;   //optional, default is iosApp<br>}<br></pre><h3>Add Colors</h3><p>In your shared module: shared&gt;src&gt;commonMain&gt;resources&gt;colors add “colors.xml”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*xCI3isPLDRhpI4BXr9DwKQ.png" /></figure><p>sample colors.xml</p><pre>&lt;resources&gt;<br>    &lt;color name=&quot;primary&quot;&gt;#FF9900&lt;/color&gt;<br>    &lt;color name=&quot;primary_two&quot;&gt;#AAFF9900&lt;/color&gt;<br>    &lt;color name=&quot;primary_three&quot;&gt;#FFF00000&lt;/color&gt;<br>&lt;/resources&gt;</pre><h3>How to use in Android</h3><p>After adding color you can run your android app or run</p><pre>./gradlew build</pre><p>Verify generated colors file at shared&gt;build&gt;generated&gt;colors&gt;generatedcolors.kt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*mfsm7ZAFGvWPxSgk0Qnv8A.png" /></figure><p>You can then simply use this color in your composable like this</p><pre>@Composable<br>fun GreetingView(text: String) {<br>    Text(text = text, color = primaryThree)<br>}</pre><h3>How to use in iOS</h3><p>Once you have already run your Android app, open iosApp.xcodeproj. On your “iosApp”, right click and click on “Add Files to “iosApp” and add “Colors.xcassets”. You should already start seeing your colors in XCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_N1IAWm0of8ZP108ZORyQ.png" /></figure><h4>Enable Asset Symbol Extensions</h4><p>select iosApp Target&gt; Build Setting, Change the value of “Generate Swift Asset Symbol Extensions” to “yes”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*AVj130q3LaXpK4aPH_7CTQ.png" /></figure><p>And use it in your swift</p><pre>struct ContentView: View {<br> let greet = Greeting().greet()<br><br> var body: some View {<br>  Text(greet)<br>    .foregroundColor(.primaryThree)<br> }<br>}</pre><p>All Set</p><h3>Using KColor from ViewModel</h3><p>If you want to set color from your ViewModels you can use generated KColorRes to set colors like this</p><p>In shared module build.gradle</p><pre>plugins {<br>    //other plugins<br>    id(&quot;io.github.mohitsoni48.KColor&quot;)<br>}<br><br>kotlin {<br><br>    sourceSets.commonMain {<br>        kotlin.srcDir(&quot;build/generated/colors&quot;)<br>    }<br>    sourceSets.androidMain {<br>        kotlin.srcDir(&quot;build/generated/android/kcolors&quot;)<br>    }<br>    sourceSets.iosMain {<br>        kotlin.srcDir(&quot;build/generated/ios/kcolors&quot;)<br>    }<br><br>    sourceSets {<br>        commonMain.dependencies {<br>            //...<br>        }<br>    }<br>}<br><br>kColor {<br>    packageName = &quot;com.mohitsoni.kcolorsample&quot;<br>    sharedModule = &quot;shared&quot; //optional, default is shared<br>    iosAppName = &quot;iosApp&quot;   //optional, default is iosApp<br>}</pre><p>In shared ViewModel</p><pre>class ColorStateViewModel: ViewModel() {<br>    val colorState: MutableStateFlow&lt;KColor&gt; = MutableStateFlow(KColorRes.primary)<br>    //.....<br>    fun setColor() {<br>        colorState.value = KColorRes.primaryTwo<br>    }<br>}</pre><p>and to use in Android and iOS you can use getColor() method which return Color from Jertpack compose in AndroidMain and UIColor in iOSMain</p><h4>In Android</h4><pre>Text(text = text, color = getColor(colorState.value))</pre><h4>In iOS</h4><p>Since in iOS kotlin has interop with Objective-C and not Swift, we get UIColor which you have to convert to Color in swift so you can create an extention func in swift</p><pre>func getColor(kColor: String) -&gt; Color {<br>    return Color(GetColorKt.getColor(kColor: kColor))<br>}</pre><p>and use it like</p><pre>Text(greet)<br>    .foregroundColor(getColor(kColor: colorState.value))</pre><p>Did this library make your work easy? Tipe me here: <a href="https://ko-fi.com/mohitsoni">https://ko-fi.com/mohitsoni</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca162411dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Pixel-Perfect UI with Jetpack Compose]]></title>
            <link>https://proandroiddev.com/creating-pixel-perfect-ui-with-jetpack-compose-17376455f16b?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/17376455f16b</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 07:43:15 GMT</pubDate>
            <atom:updated>2024-08-27T15:15:04.726Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever built an Android app, you’ve likely faced complaints from your design team about UI elements not matching the size in their design files. It can be frustrating to explain that you’ve followed the design specs to the letter, yet the results vary across devices. This back-and-forth discussion seems to resurface with every project, often without a clear solution. But that’s about to change. In this article, I’ll show you how to create pixel-perfect UI for any device spec in Jetpack Compose using a library called “aDp.”</p><h3>Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMGFjnEwpEZe4uSjhfKTGQ.png" /></figure><p>If you’ve ever examined your design file closely, you might have noticed that the width in pixels never matches the resolution of your device. For instance, while your device might have a resolution of 2460x1080, the design file might only show a resolution of 800x360.</p><h4>How does it even work then?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qK2erYNHGCb93Hv3oVCdhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSURcijn18lPdPJczF7o8Q.png" /></figure><p>This is a fundamental aspect of how Android’s dimensions in dp work, whether you’re using XML or Jetpack Compose. Android’s official documentation covers this topic thoroughly, so I won’t delve into it here.</p><h4>But there is a catch — Display Zoom Setting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkEAZwy9TD9sBdByz6QcGA.png" /></figure><p>In Android, there’s a setting called “Display size” — though the name may vary across different device manufacturers. This setting allows users to adjust the size of the display content. When this setting is changed, the same app with identical dimensions can appear differently in size. For instance, here’s how WhatsApp looks on the same device with different zoom settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HT4caVLL717pRXa0Q_fogw.png" /></figure><h4>What Actually Changes?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6wl_KVlMf63VnawiRL7JA.png" /></figure><p>If you check the “Smallest width” option in your device’s Developer Options, you’ll notice that this value changes when you adjust the display size.</p><h4>What is Smallest Width?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pf9EV9yY3YdS7QOpBbjpA.png" /></figure><p>In simple terms, the smallest width represents the width of the screen in dp. To simplify further, if the smallest width is 360, a rectangle with a width of 360dp will fill the entire screen. If the smallest width is 720, then that same 360dp rectangle will only fill half the screen’s width.</p><h3>Solution</h3><p>While changes in display zoom are intended to alter the appearance of your app — aligned with Google’s Accessibility guidelines — they may not always be beneficial, especially if your app includes complex, custom views. In such cases, you may want your views to adapt more precisely to the device’s settings. For this, you can use a library called “aDp.”</p><p>Github repo: <a href="https://github.com/mohitsoni48/aDp">https://github.com/mohitsoni48/aDp</a></p><h4>How it works?</h4><p>This library takes the design width as input and then scales all your dimensions according to the device’s settings, ensuring they match the design file precisely. For example, here’s a comparison of two TextViews: with a design width of 360, you can see how the TextView using standard dp changes, while the one using aDp adjusts itself to look nearly identical to the design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxtCa9Gw49kvwW0vj9DnJA.png" /></figure><h4>Did I just mention Text View?</h4><p>The same issue applies to fonts. If users adjust their device’s font size to Large or Largest, your design is likely to break, as it may not scale properly with the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vt4d0txnXlk8o606Wl603w.png" /></figure><p>Similar to how sp is used for fonts, this library includes a separate unit for fonts: aSp, which operates on the same principle.</p><h3>Conlusion</h3><p>While it’s generally advisable for your app to adapt to changes in display size and font size, this isn’t always feasible, especially with complex and custom views. In such cases, aDp and aSp are invaluable, as they ensure your views remain consistent across all devices and settings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17376455f16b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/creating-pixel-perfect-ui-with-jetpack-compose-17376455f16b">Creating Pixel-Perfect UI with Jetpack Compose</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to “get()” your Koin dependency in iOS]]></title>
            <link>https://proandroiddev.com/how-to-get-your-koin-dependency-in-ios-efb6d83ee165?source=rss-cc53cf151c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb6d83ee165</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Mohitsoni]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 16:08:33 GMT</pubDate>
            <atom:updated>2024-09-29T03:26:44.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NRd4lhsYBMw4l5ApIQ-DA.jpeg" /></figure><p>With the growing popularity of Kotlin Multiplatform (KMP), various Kotlin-based tools have seen significant evolution, one of which is the Dependency Injection framework “Koin.” Using Koin for DI in Android and iOS within a KMP project presents both advantages and challenges. Despite being the most popular DI framework in KMP, Koin has limitations, particularly when it comes to accessing instances in your iOS Swift module. In this article, I’ll guide you on how to effortlessly “get()” your instances in iOS, just as you would in your Kotlin module.</p><h4>Setup</h4><p>I will skip the basic setup part as it is well documented in Koin’s official documentation and there is not much to change.</p><h4>Problem</h4><p>In a Kotlin Multiplatform (KMP) project, once you’ve set up your Koin application with defined modules, injecting dependencies into your Kotlin classes is straightforward using the KoinComponent interface. However, KoinComponent isn&#39;t available in iOS, which complicates dependency injection. To address this, you&#39;ll need to create a custom &quot;Provider&quot; for your instances.</p><pre>val viewmodelModule = module {<br>    factory { SplashViewModel(get(), get()) }<br>    //..other dependencies<br>}</pre><pre>object PresenterProvider: KoinComponent {<br>    fun provideSplashViewModel(): SplashViewModel = get()<br>    //..similar functions for all your dependencies<br>}</pre><p>And to use in in iOS</p><pre>@StateObject var splashViewModel: SplashViewModel = PresenterProvider.shared.provideSplashViewModel()</pre><p>This approach can feel cumbersome, requiring additional overhead to create a provider. Moreover, the way to access these dependencies in Swift isn’t as clean or straightforward as in Kotlin.</p><h4>Solution</h4><p>To address this issue, we will create our own custom get() method in Swift that replicates the functionality of the Kotlin get() method, allowing us to retrieve dependencies seamlessly within the iOS environment.</p><h4>Step 1: Obtain the Koin Application Instance</h4><p>Koin’s documentation provides a brief guide on initializing your Koin application from iOS. This step is crucial as it sets up the foundation for dependency injection across both your Kotlin and Swift modules.</p><pre>//This method is called from App class of your ios project<br>fun initKoin(){<br>    startKoin {<br>        modules(appModule())<br>    }<br>}</pre><p>While this approach works, we can unlock even more potential by fully utilizing the startKoin function. This function returns the Koin application, which allows us to load/unload modules and even retrieve instances with get(). To leverage this in iOS, we can modify the dependency helper in iosMain as follows.</p><pre>class DependenciesProviderHelper {<br>    fun initKoin() {<br><br>        val iosModule = module {<br>            //your ios modules<br>        }<br><br>        val instance = startKoin {<br>            modules(getBaseModules() + iosModule)<br>        }<br><br>        koin = instance.koin<br>    }<br><br>    companion object {<br>        lateinit var koin: Koin<br>    }<br>}</pre><h4>Step 2: Creating Methods to Retrieve Instances</h4><p>We need to implement a method in Kotlin that is interoperable with Swift, allowing us to retrieve instances using generics. To achieve this, we will create two methods outside the DependencyProviderHelper class, located in iosMain.</p><pre>@OptIn(BetaInteropApi::class)<br>fun Koin.get(objCClass: ObjCClass): Any {<br>    val kClazz = getOriginalKotlinClass(objCClass)!!<br>    return get(kClazz, null, null)<br>}<br><br>@OptIn(BetaInteropApi::class)<br>fun Koin.get(objCClass: ObjCClass, qualifier: Qualifier?, parameter: Any): Any {<br>    val kClazz = getOriginalKotlinClass(objCClass)!!<br>    return get(kClazz, qualifier) { parametersOf(parameter) }<br>}</pre><p>Now we simply need to call these methods from swift using the koin instance that we already have</p><pre>func get&lt;A: AnyObject&gt;() -&gt; A {<br>    return DependenciesProviderHelper.companion.koin.get(objCClass: A.self) as! A<br>}<br><br>func get&lt;A: AnyObject&gt;(_ type: A.Type) -&gt; A {<br>    return DependenciesProviderHelper.companion.koin.get(objCClass: A.self) as! A<br>}<br><br>func get&lt;A: AnyObject&gt;(_ type: A.Type, qualifier: (any Koin_coreQualifier)? = nil, parameter: Any) -&gt; A {<br>    return DependenciesProviderHelper.companion.koin.get(objCClass: A.self, qualifier: qualifier, parameter: parameter) as! A<br>}</pre><h4>Step 3: Using these get methods</h4><p>Once implemented, you can seamlessly use these methods throughout your app. For example:</p><pre>var splashViewModel: SplashViewModel = get()</pre><p>That’s all.</p><p>If you’re interested in learning how to get() an observable object and simplify the use of Kotlin ViewModels in Swift, let me know in the comments. I’d be happy to write a follow-up post on that topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb6d83ee165" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/how-to-get-your-koin-dependency-in-ios-efb6d83ee165">How to “get()” your Koin dependency in iOS</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>