<?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 Khush Panchal on Medium]]></title>
        <description><![CDATA[Stories by Khush Panchal on Medium]]></description>
        <link>https://medium.com/@khush.panchal123?source=rss-7c3779710486------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IP5p0VK2dAMHTF6_</url>
            <title>Stories by Khush Panchal on Medium</title>
            <link>https://medium.com/@khush.panchal123?source=rss-7c3779710486------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:18:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khush.panchal123/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[What even is an AI Agent?… Isn’t it just an API Call?]]></title>
            <link>https://medium.com/@khush.panchal123/what-even-is-an-ai-agent-isnt-it-just-an-api-call-5aa62c904164?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa62c904164</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 06:22:40 GMT</pubDate>
            <atom:updated>2026-03-31T06:22:40.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSP-70B2nNfQq9d5CXLZ7w.png" /></figure><p>If you’ve been hearing <em>“agents will do everything”</em> and thinking…</p><blockquote>“Isn’t this just a GPT API with a fancy wrapper?”</blockquote><p>You’re not alone.</p><p>Here’s the simple truth:</p><ul><li>An <strong>LLM</strong> (like GPT-5) is like a very powerful <strong>text-predicting brain</strong>.</li><li>An <strong>Agent</strong> is the <strong>system you build around that brain</strong>.</li></ul><p>Let’s simplify what happens behind the scenes. Please note this is the beginner’s guide, we’ll skip the jargon and explain how things work, in layman’s terms.</p><h3>LLM — The “black box” that answers in English</h3><p>Let’s start super basic.</p><p>An LLM (Large Language Model) is trained to do one main thing:</p><blockquote>Given some text, predict what text should come next.</blockquote><p>It doesn’t “think” the way humans do. It predicts the next pieces of text using patterns it learned from a vast amount of reading. That’s literally how large language models are trained.</p><p>Let’s understand this a bit more with an example.</p><h4>What happens when you ask: “How does a Car Engine work?”</h4><p>In the simplest possible story:</p><ul><li>Your sentence is split into <strong>tokens</strong> (numbers — computers love numbers).</li><li>The model uses a huge set of learned numbers (the “black box” — the LLM) to predict the next token.</li></ul><p>In short, this LLM is using <strong>Machine Learning</strong> behind the scenes.</p><p>It is fed with lots of data (scraped from the internet over the years), learns patterns from that data, and when a new set of numbers is given, it predicts the best possible next response as numbers — which are eventually converted back to text again.</p><p>That’s it.</p><h4>Mini LLM pseudo code</h4><pre>def mini_llm(prompt_text):<br>    # 1) Break text into tokens (tiny chunks) because computers work on numbers<br>    token_ids = tokenize(prompt_text)<br><br>    # 2) Predict next token again and again<br>    while not stop_condition(token_ids):<br>        next_id = black_box_predict_next(token_ids)  # &quot;best next number&quot; (probability-based)<br>        token_ids.append(next_id)<br><br>    # 3) Convert numbers back to readable text<br>    return to_text(token_ids)</pre><p>This “predict next token” idea, and the repeated loop, is a standard way to describe how modern text-generation systems (LLMs) produce outputs.</p><p>Some private model examples are GPT-5, Gemini 2.5 Pro, Opus 4.5, and so on.</p><h3>Now say you take any model and ask:</h3><blockquote>“What’s happening today in India?”</blockquote><p>It will not be able to answer properly on its own.</p><p>As we discussed, a model is something pre-trained with lots of data, and now it understands how to answer questions based on that knowledge. But if you ask the model about <em>today</em> or any <em>current information</em>, it will not reliably know the answer.</p><p>So how do we solve that?</p><h4>Train the model daily?</h4><p>Issue — Training big models is <strong>crazy expensive (like millions of dollars)</strong>.</p><p>That’s why a pure pretrained model may confidently answer “how engines work” but struggle with “what happened today”.</p><p>But then how is it that when you type the same query in ChatGPT, it is able to answer properly?</p><p>And this is where <strong>RAG</strong> comes in.</p><h3>RAG in one line: Search + Attach + Answer</h3><p>RAG full form is:</p><p><strong>Retrieval‑Augmented Generation</strong></p><ul><li><strong>Retrieval</strong> = go and fetch the right info (like searching)</li><li><strong>Augmented</strong> = attach that info to your question</li><li><strong>Generation</strong> = write the final answer</li></ul><p>They don’t “retrain the brain”.<br>They connect the brain to fresh information through external sources.</p><p>A beginner mental model:</p><blockquote>RAG turns the AI from “closed book exam” into an “open book exam”.</blockquote><p>Now if you ask <em>“what’s today’s news?”</em>, I can call a News API, get today’s news, and then silently update the actual prompt I send to the LLM by passing the API data I received from the News API.</p><p>Now the LLM knows what to answer, and you see the response you actually wanted.</p><p>That’s RAG — passing an external source of information to the LLM.</p><h4>Mini RAG pseudo code (simple version)</h4><pre>def mini_rag(question):<br>    # Step 1: Retrieval (search some knowledge source)<br>    context = search_news(question)  # returns response from News API<br><br>    # Step 2: Augment (attach context to the question)<br>    prompt = f&quot;&quot;&quot;<br>    Use the CONTEXT to answer the QUESTION.<br><br>    CONTEXT:<br>    {context}<br><br>    QUESTION:<br>    {question}<br>    &quot;&quot;&quot;<br><br>    # Step 3: Generation (write the answer)<br>    return mini_llm(prompt)</pre><p>But now a big question:</p><p>How does the AI system know that it has to call search_news()?</p><p>What if the user asks <em>“What’s the weather in India today?”</em></p><p>This time you need a <strong>weather API</strong>, not a <strong>news API</strong>.</p><p>This is where <strong>MCP</strong> comes into the picture.</p><h3>MCP: A protocol for tools, like HTTP is a protocol for web APIs</h3><p>In normal software, we have a simple idea:</p><p>HTTP is a standard way for apps to talk to servers.</p><p>Because of HTTP, your app can call 1,000 different APIs in a predictable way.</p><p>MCP (Model Context Protocol) tries to do something similar for AI systems:</p><blockquote>A standard way for an AI app to connect to external tools and data sources.</blockquote><p>It was introduced as an open standard to make secure, two-way connections between AI apps and tools/data.</p><p>MCP is the “common language” between your agent and your tools.</p><p>Now, in the structure of MCP, there is metadata that contains the description of that MCP.</p><p>So how does this MCP help us solve the problem?</p><p>MCP has a structure where each MCP has a description of what it does. We call that <strong>metadata</strong>.</p><p>For example News MCP have:</p><pre>{<br> &quot;name&quot;: &quot;news.latest&quot;<br> &quot;description&quot;: &quot;Get today&#39;s latest headlines for a topic&quot;<br>}</pre><p>And this News MCP when called will internally use news API to fetch the data and then the MCP will return the response.</p><p>So now the question changes to:</p><blockquote>How does the LLM know which MCP to call?</blockquote><p>So the general flow becomes:</p><p>When we ask <em>“What’s today’s news?”</em>, the AI system silently adds the metadata of all available MCPs to the prompt request sent to the LLM and then asks the LLM: if you don’t know the answer directly, choose the correct MCP that does know.</p><p>And the LLM, based on its strength in understanding English and descriptions, can correctly identify which MCP should be called for which question.</p><p>Then we can call search_news(), and again go back to the LLM — this time with the news information — and perform our RAG.</p><blockquote>MCP vs RAG (the clean difference) — <strong>RAG</strong> is the <em>idea</em>: retrieve info, attach it, answer. <strong>MCP</strong> is the <em>standard connection method</em> to tools and data.</blockquote><h3>Agent: the backend “manager” that makes automation real</h3><p>Now we reach the main hook of this blog:</p><blockquote>An agent is not the brain. It’s the system.</blockquote><p>The LLM is the “brain that writes”.</p><p>The <strong>Agent</strong> is the system that:</p><ul><li>reads your request,</li><li>decides if a tool is needed,</li><li>calls that tool,</li><li>and then asks the LLM to write the final reply using tool results.</li></ul><p>This “tool-calling flow” is explicitly a multi-step conversation:</p><p>send tools → model chooses tool → we execute tool → send tool output → model produces final response</p><h4>Big picture architecture: apps → backend agent → tools/LLM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZe_rkMt2d1Q-nYSZxq8Rw.png" /></figure><p>This matches how tool calling is designed in modern LLM APIs: the application (backend) sits in the middle, executes tools, and feeds results back to the model.</p><h4>The simple “Latest news today” flow you asked to LLM</h4><p>User question:</p><blockquote>“What’s the latest news today in India?”</blockquote><p>We’ll show the exact path, and what data is sent at each step.</p><h4>Key detail: the model first receives the tool menu, not the tool result</h4><p>When your backend contacts the LLM initially, it sends:</p><ul><li>the question,</li><li>tool descriptions (what tools exist, what they do, what inputs they accept)</li></ul><h4>Step-by-step sequence diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibjJF5FfAttf-KKlFBH25g.png" /></figure><p>The “model asks for a tool, app executes it, then model answers” pattern is exactly how tool calling works.</p><h4>Example pseudo code</h4><pre>TOOLS = [<br>  {<br>    &quot;name&quot;: &quot;news.latest&quot;,<br>    &quot;description&quot;: &quot;Get today&#39;s latest headlines for a topic&quot;,<br>    &quot;inputs&quot;: {&quot;query&quot;: &quot;text&quot;}<br>  }<br>]<br><br>def agent_answer(question):<br>    # 1) Ask the LLM with the tool descriptions (menu)<br>    first = llm_call(<br>        prompt=question,<br>        tools=TOOLS<br>    )<br><br>    # 2) If LLM says: &quot;use the news tool&quot;, backend runs it<br>    if first.type == &quot;tool_request&quot; and first.tool_name == &quot;news.latest&quot;:<br>        news = mcp_call(&quot;news.latest&quot;, {&quot;query&quot;: first.args[&quot;query&quot;]})<br><br>        # 3) Ask LLM again, now including the fresh news data<br>        final = llm_call(<br>            prompt=f&quot;Question: {question}\nFresh news data: {news}\nExplain simply.&quot;,<br>            tools=[]<br>        )<br>        return final.text<br><br>    # If no tool needed, return what model wrote directly<br>    return first.text</pre><p>Again: the LLM doesn’t “browse”.</p><p>Your backend agent does the tool calls, then the model writes the final message.</p><h4>One more tiny example: “2 + 2”</h4><p>Here’s the beginner-friendly punchline:</p><p>LLMs are great at language, but for guaranteed maths, you can use a <strong>Calculator MCP</strong>.</p><p>So your agent can do:</p><ul><li>If question looks like maths → use Calculator MCP</li><li>Then ask the LLM to explain nicely.</li></ul><p>This is the same tool calling loop, just with a different tool.</p><h4>Calendar agent</h4><p>A calendar agent works because you give the backend:</p><ul><li>a calendar tool (via MCP),</li><li>and the LLM can choose it based on the tool description.</li></ul><p>So:</p><blockquote>“Schedule a meeting tomorrow 5 pm”</blockquote><p>becomes:</p><ul><li>model asks to call calendar.create_event,</li><li>backend calls it,</li><li>model confirms.</li></ul><p>That “agent loop with tools + optional human approvals” is also a core pattern described in agent systems.</p><h3>The simplest takeaway</h3><p>If you remember only one thing, remember this:</p><ul><li>LLM = Machine learning brain that predicts text (token-by-token)</li><li>RAG = Give the brain fresh notes before it speaks</li><li>MCP = A protocol that plugs tools into your AI system</li><li>Agent = Your backend system that connects brain + tools + loop</li></ul><p>That’s why “agents” are not just an API call.</p><p>They are system design.</p><p>And once you see that, all those “agent agent agent” discussions stop sounding like magic — and start sounding like engineering.</p><p><strong>Contact Me:</strong> <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a> | <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa62c904164" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run Your MVVM Android App on iOS — KMP Magic ✨]]></title>
            <link>https://medium.com/@khush.panchal123/run-your-mvvm-android-app-on-ios-kmp-magic-d6c9e8b148cd?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c9e8b148cd</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 14:10:51 GMT</pubDate>
            <atom:updated>2026-01-25T14:10:51.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Run Your MVVM Android App on iOS — KMP Magic ✨</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlA6pQDBDxanM0VyneQ2Vw.png" /></figure><p>In this article, we’ll take an existing Android MVVM app and gradually convert it into a Kotlin Multiplatform (KMP) app — without rewriting the business logic.</p><p>The goal is simple:</p><blockquote>Share business logic (repository, networking, database) across Android and iOS, while keeping UI native.</blockquote><h4>Out of scope for this article</h4><ul><li>To keep things simple and focused, we will not cover:</li><li>Common UI (Compose Multiplatform)</li><li>Common ViewModel</li><li>Publishing shared module remotely (KMMBridge / SPM)</li></ul><blockquote>We want clarity first, not complexity.</blockquote><h4>Outline of our article</h4><ul><li>Android only MVVM app (Starting point)<br>- Feature of sample app<br>- Basic outline of android project<br>- How data flows (mental model)<br>- Clone and run the android app</li><li>Setup the KMP world<br>- What’s important from the official guide (summary)</li><li>Beginning the KMP magic<br>- Step 1: Move data folder to the shared module<br>- Step 2: Replace Hilt with Koin (Multiplatform DI)<br>- Step 3: Replace Retrofit with Ktor<br>- Step 4: Replace Room with Room KMP<br>- Step 5: Create UI and ViewModel alternative for IOS</li><li>Final words</li></ul><h3>Android only MVVM app (Starting point)</h3><p>We begin with an Android-only MVVM application that follows a clean and well-structured architecture.</p><p><strong>Source code (master branch) — </strong><a href="https://github.com/khushpanchal/MultiplatformMoviesApp/tree/master"><strong>Link</strong></a></p><h4>Features of the sample app</h4><ul><li>Movies app using <a href="https://www.omdbapi.com/">OMDb free API</a></li><li>Offline-first architecture (Database acts as a single source of truth, refer <em>MovieRepository.kt</em> file for implementation)</li><li>Two screens:<strong> </strong>Movie list screen (Uses MovieViewModel and shows a list of movies), Movie detail screen (simple UI, no ViewModel)</li><li>Uses: Retrofit → Networking; Room → Local caching; Hilt → Dependency Injection; Jetpack Compose → UI</li></ul><h4>Basic outline of the android project</h4><pre><br>└── com.khush.moviesapp<br>    ├── data<br>    │   ├── database<br>    │   │   ├── DatabaseService.kt<br>    │   │   ├── MovieDao.kt<br>    │   │   ├── MovieDatabase.kt<br>    │   │   └── MovieDatabaseService.kt<br>    │   ├── model<br>    │   │   └── MovieData.kt<br>    │   ├── network<br>    │   │   └── ApiInterface.kt<br>    │   ├── repository<br>    │   │   └── MovieRepository.kt<br>    │   └── utils<br>    │       └── Const.kt<br>    ├── di<br>    │   └── module<br>    │       └── ApplicationModule.kt<br>    ├── ui<br>    │   ├── viewmodel<br>    │   │   ├── MovieViewModel.kt<br>    │   │   └── UIState.kt<br>    │   ├── DetailScreen.kt<br>    │   ├── MovieActivity.kt<br>    │   └── MovieScreen.kt<br>    └── MovieApplication.kt</pre><h4>How data flows (mental model)</h4><ul><li>UI observes ViewModel</li><li>ViewModel talks to Repository</li><li>Repository decides: fetch from DB or fetch from API</li><li>UI reacts to changes in UIState</li></ul><blockquote>This mental model is important — we’ll preserve it even after KMP.</blockquote><h4>Clone and run the Android app</h4><p>Before touching KMP, always verify the base app works.</p><ol><li>Clone the repo (<a href="https://github.com/khushpanchal/MultiplatformMoviesApp/tree/master">master branch</a>)</li><li>Generate an API key from <a href="https://www.omdbapi.com/">https://www.omdbapi.com/</a></li><li>Add the API key inside <em>Const.kt</em></li><li>Run the Android app</li></ol><p>We should see the movie list screen working correctly.</p><h3>Setup up the KMP world</h3><p>Before converting our Android MVVM app to a KMP MVVM app, we must ensure the KMP environment is correctly set up.</p><p>We will follow the official Kotlin guide for integrating KMP into an existing Android app — <a href="https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html">https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html</a></p><p>You can follow this guide end-to-end. At this stage:<br>- Nothing meaningful will be shown on iOS yet<br>- Our goal is only to ensure the project builds and runs on both platforms</p><h4>What’s important from the official guide (summary)</h4><ul><li>Create a shared module for cross-platform code — <a href="https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html#create-a-shared-module-for-cross-platform-code">Link</a><br>- Once created, we’ll see three important folders:</li></ul><pre>- commonMain - common kotlin code, accessible by both android and ios<br>- androidMain - android specific implementations, can use android sdk<br>- iosMain - ios specific implementations, can use ios platform apis</pre><ul><li>Add code to the shared module — <a href="https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html#add-code-to-the-shared-module">Link</a> <br>- This allows Android code to access shared Kotlin code. We can see the use of expect/actual in the example, let’s understand the basics</li></ul><blockquote>KMP allows us to declare what we need in common code, and define how it works per platform.</blockquote><blockquote>- expect class — written in commonMain — method declaration without implementation<br>- actual class — written in androidMain or iosMain with platform specific implementation</blockquote><blockquote>Whenever common code needs different behavior on Android and iOS, we use expect/actual.</blockquote><ul><li>Add a dependency on the shared module to your Android application — <a href="https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html#add-a-dependency-on-the-shared-module-to-your-android-application">Link</a></li><li>Now we will run our cross-platform application on Android</li><li>Make your cross-platform application work on iOS — <a href="https://kotlinlang.org/docs/multiplatform/multiplatform-integrate-in-existing-app.html#make-your-cross-platform-application-work-on-ios">Link</a><br>- Follow all four steps and finally verify that shared module can be imported in Swift and iOS app builds and runs successfully</li></ul><p>Optional (but recommended): Install Kotlin Multiplatform plugin</p><ul><li>Android Studio Settings → Plugins → Marketplace → Kotlin Multiplatform</li><li>This helps with: Environment checks, Project configuration, Boilerplate generation (<em>We can do KMP without the plugin, but it smoothens the experience)</em></li></ul><h3>Beginning the KMP magic ✨</h3><p>At this point:<br> • Android app works<br> • iOS app builds<br> • Shared module is ready<br> • KMP pipeline is validated</p><p>Now we are finally ready to convert our Android MVVM app into a KMP MVVM app.</p><blockquote>At any point, you can refer to the full conversion Pull Request for comparison.</blockquote><blockquote>PR — <a href="https://github.com/khushpanchal/MultiplatformMoviesApp/pull/1/files">Android → KMP conversion</a></blockquote><p>Highlights of what we will be doing</p><ul><li>Moving our data folder from app module to shared module</li><li>Replace Android only libraries to KMP compatible libraries<br>- Hilt → Koin (Dependency Injection)<br>- Retrofit → Ktor (Networking) (Additionally Gson → Kotlin Serialization)<br>- Room → Room KMP (Database)</li><li>Create native UI and ViewModel in swift for IOS</li></ul><h4>Step 1: Move data folder to the shared module</h4><p>The data layer is the most natural candidate for sharing.</p><p><strong>What we move</strong></p><p>Move the entire <em>data</em> package from:</p><pre>app/src/main/java</pre><p>to:</p><pre>shared/src/commonMain/kotlin</pre><p>This includes: database, network, repository, model, utils</p><p>At this point, <strong>the project will break</strong> — this is expected.</p><p>We’ll fix things step by step.</p><p><strong>Clean up Android-only dependencies</strong></p><p>Since data logic is now shared, we must remove Android-only dependencies from app.</p><p>Remove from <em>app/build.gradle.kts</em>: Hilt, Retrofit, Room, kapt (we’ll use <strong>KSP</strong> instead)</p><h4>Step 2: Replace Hilt with Koin (Multiplatform DI)</h4><p>Hilt is Android-only, so we replace it with <strong>Koin</strong>, which works on both Android and iOS.</p><p>Remove all Hilt annotations</p><pre>@HiltViewModel, @AndroidEntryPoint, @HiltAndroidApp, @Inject constructor</pre><p>Also delete: <em>ApplicationModule.kt</em> (Hilt module)</p><p>Create Android-specific Koin module in App module folder, and Shared module in commonMain folder.</p><pre>#AppModule.kt<br><br>val appModule = module {<br>    viewModel {<br>        MovieViewModel(<br>            movieRepository = get()<br>        )<br>    }<br>}<br><br>###################################<br><br>#SharedModule.kt<br><br>val sharedModule = module {<br>   single&lt;MovieRepository&gt; {<br>        MovieRepository(<br>            apiInterface = get(),<br>            databaseService = get()<br>        )<br>    }<br>}<br></pre><p>Now we will add koin related dependencies</p><pre>#libs.version.toml<br><br>koin-bom = &quot;4.1.1&quot;<br><br>koin-bom = { module = &quot;io.insert-koin:koin-bom&quot;, version.ref = &quot;koin-bom&quot; }<br>koin-core = { module = &quot;io.insert-koin:koin-core&quot; }<br>koin-android = { module = &quot;io.insert-koin:koin-android&quot; }<br>androidx-startup-runtime = { group = &quot;androidx.startup&quot;, name = &quot;startup-runtime&quot;, version.ref = &quot;startupRuntime&quot; }<br><br>###################################<br><br>#App Module build.gradle.kts<br><br>dependencies {<br>    implementation(project.dependencies.platform(libs.koin.bom))<br>    implementation(libs.koin.android)<br>}<br><br>###################################<br><br>#Shared Module build.gradle.kts<br><br>commonMain {<br>    dependencies {<br>        implementation(project.dependencies.platform(libs.koin.bom))<br>        implementation(libs.koin.core)<br>    }<br>}</pre><p>Sync Gradle and then update <em>MovieApplication.kt</em> and <em>MovieActivity.kt</em> files</p><pre>#MovieApplication.kt<br><br>class MovieApplication: Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        // Initialize Koin on Android<br>        startKoin {<br>            androidContext(this@MovieApplication)<br>            modules(listOf(appModule, sharedModule))<br>        }<br>    }<br>}<br><br>###################################<br><br>#MovieActivity.kt<br><br>class MovieActivity : ComponentActivity() {<br><br>    // Inject ViewModel<br>    private val movieViewModel: MovieViewModel by inject()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MainScreen(movieViewModel = movieViewModel, ...)<br>        ...<br>    }<br>}</pre><h4>Step 3: Replace Retrofit with Ktor</h4><p>Retrofit is Android-only.</p><p>We replace it with <strong>Ktorfit</strong> (built upon Ktor), which gives us a Retrofit-like API but works on KMP.</p><p>To do it we will add Ktor, Ktorfit and Kotlin Serialization dependency (We will replace with Gson used in android project). We will also need KSP for this.</p><pre>#libs.version.toml<br><br>ktor = &quot;3.3.3&quot;<br>ktorfit = &quot;2.7.2&quot;<br>ksp = &quot;2.3.4&quot;<br><br>ktor-client-core = { module = &quot;io.ktor:ktor-client-core&quot;, version.ref = &quot;ktor&quot; }<br>ktor-serialization = { module = &quot;io.ktor:ktor-serialization-kotlinx-json&quot;, version.ref = &quot;ktor&quot; }<br>ktor-client-content-negotiation = { module = &quot;io.ktor:ktor-client-content-negotiation&quot;, version.ref = &quot;ktor&quot; }<br>ktorfit-lib = {module = &quot;de.jensklingenberg.ktorfit:ktorfit-lib&quot;, version.ref = &quot;ktorfit&quot; }<br><br>[plugins]<br>ksp = { id = &quot;com.google.devtools.ksp&quot;, version.ref = &quot;ksp&quot; }<br>ktorfit = { id = &quot;de.jensklingenberg.ktorfit&quot;, version.ref = &quot;ktorfit&quot; }<br>kotlinxSerialization = { id = &quot;org.jetbrains.kotlin.plugin.serialization&quot;, version.ref = &quot;kotlin&quot; }<br><br>###################################<br><br>#Project level build.gradle.kts<br><br>alias(libs.plugins.ksp) apply false<br>alias(libs.plugins.ktorfit) apply false<br>alias(libs.plugins.kotlinxSerialization) apply false<br><br>###################################<br><br>#Shared module build.gradle.kts<br><br>alias(libs.plugins.ksp)<br>alias(libs.plugins.ktorfit)<br>alias(libs.plugins.kotlinxSerialization)<br><br>commonMain {<br>    dependencies {<br>        // Ktor<br>        implementation(libs.ktor.client.core)<br>        implementation(libs.ktor.client.content.negotiation)<br>        implementation(libs.ktor.serialization)<br><br>        // Ktorfit<br>        implementation(libs.ktorfit.lib)<br>}</pre><p>We will use the same ApiInterface.kt class just replace the imports</p><pre>#ApiInterface.kt<br><br>import de.jensklingenberg.ktorfit.http.GET<br>import de.jensklingenberg.ktorfit.http.Query<br><br>interface ApiInterface {<br>    @GET(&quot;.&quot;)<br>    suspend fun getMoviesData(<br>        @Query(&quot;s&quot;) s: String = &quot;army&quot;,<br>        @Query(&quot;apikey&quot;) apikey: String = Const.API_KEY<br>    ): ApiResponse<br>}</pre><p>We will add the dependency in shared module class for Ktorfit</p><pre>#SharedModule.kt<br><br>val sharedModule = module {<br>    single&lt;ApiInterface&gt; {<br>        val ktorfit = Ktorfit<br>            .Builder()<br>            .baseUrl(Const.BASE_URL)<br>            .httpClient(<br>                HttpClient {<br>                    install(ContentNegotiation) {<br>                        json(<br>                            Json {<br>                                isLenient = true<br>                                ignoreUnknownKeys = true<br>                                prettyPrint = true<br>                            }<br>                        )<br>                    }<br>                }<br>            )<br>            .build()<br><br>        ktorfit.createApiInterface()<br>    }<br>}</pre><p><strong>To use Kotlin Serialization</strong>, inside <em>MovieData.kt</em> replace <em>@Serializable</em> with <em>@SerialName</em>, add <em>@Serializable</em> over data classes</p><h4>Step 4: Replace Room with Room KMP</h4><p>We will now replace room with KMP supported Room version.</p><p>We will add the dependency for room and all necessary configurations.</p><pre>#libs.version.toml<br><br>room = &quot;2.8.4&quot;<br>sqlite = &quot;2.6.2&quot;<br>koin-bom = &quot;4.1.1&quot;<br>startupRuntime = &quot;1.2.0&quot;<br><br>androidx-room-runtime = { group = &quot;androidx.room&quot;, name = &quot;room-runtime&quot;, version.ref = &quot;room&quot; }<br>androidx-room-compiler = { group = &quot;androidx.room&quot;, name = &quot;room-compiler&quot;, version.ref = &quot;room&quot; }<br>androidx-sqlite-bundled = { module = &quot;androidx.sqlite:sqlite-bundled&quot;, version.ref = &quot;sqlite&quot; }<br>androidx-startup-runtime = { group = &quot;androidx.startup&quot;, name = &quot;startup-runtime&quot;, version.ref = &quot;startupRuntime&quot; }<br><br>[plugins]<br>androidx-room = { id = &quot;androidx.room&quot;, version.ref = &quot;room&quot; }<br><br>###################################<br><br>#Project level build.gradle.kts<br><br>alias(libs.plugins.androidx.room) apply false<br><br>###################################<br><br>#Shared Module build.gradle.kts<br><br>alias(libs.plugins.androidx.room)<br><br>commonMain {<br>  dependencies {<br>      // Room<br>      implementation(libs.androidx.room.runtime)<br>      implementation(libs.androidx.sqlite.bundled)<br>  }<br>}<br>androidMain {<br>  dependencies {<br>    implementation(libs.androidx.startup.runtime)<br>  }<br>}<br>room {<br>    schemaDirectory(&quot;$projectDir/schemas&quot;)<br>}<br>dependencies {<br>    add(&quot;kspAndroid&quot;, libs.androidx.room.compiler)<br>    add(&quot;kspIosSimulatorArm64&quot;, libs.androidx.room.compiler)<br>    add(&quot;kspIosX64&quot;, libs.androidx.room.compiler)<br>    add(&quot;kspIosArm64&quot;, libs.androidx.room.compiler)<br>}<br><br>###################################<br><br>#proguard-rules.pro<br><br>-keep class * extends androidx.room.RoomDatabase { &lt;init&gt;(); }</pre><p>We need to modify <em>MovieDatabase.kt</em> class definition</p><pre>#MovieDatabase.kt<br><br>@Database(entities = [MovieData::class], version = 1, exportSchema = false)<br>@ConstructedBy(MovieDatabaseConstructor::class)<br>abstract class MovieDatabase : RoomDatabase() {<br><br>    abstract fun getMovieDao(): MovieDao<br><br>}<br><br>// The Room compiler generates the `actual` implementations.<br>@Suppress(&quot;KotlinNoActualForExpect&quot;)<br>expect object MovieDatabaseConstructor : RoomDatabaseConstructor&lt;MovieDatabase&gt; {<br>    override fun initialize(): MovieDatabase<br>}</pre><p>Now we will create the instance inside <em>SharedModule.kt</em></p><pre>val sharedModule = module {<br>  single&lt;DatabaseService&gt; {<br>        MovieDatabaseService(<br>            getDatabaseBuilder()<br>                .setDriver(BundledSQLiteDriver())<br>                .setQueryCoroutineContext(Dispatchers.IO)<br>                .build()<br>        )<br>    }<br>}</pre><p>You can see <em>getDatabaseBuilder()</em> which is needed for Room to create Database instance, we need to create the<em> RoomDatabase.Builder</em> instance separately for platform specific modules (android and ios).</p><p>Before creating expect actual method for database builder, we need app context for creating it for android platform module, we will create it using <strong>app startup library</strong> that we have added in dependency in <em>androidMain</em> module</p><pre>#androidMain folder AndroidManifest.xml file<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br>    &lt;application&gt;<br>        &lt;provider<br>            android:name=&quot;androidx.startup.InitializationProvider&quot;<br>            android:authorities=&quot;${applicationId}.androidx-startup&quot;<br>            android:exported=&quot;false&quot;<br>            tools:node=&quot;merge&quot;&gt;<br>            &lt;meta-data<br>                android:name=&quot;com.khush.shared.data.database.AppContextInitializer&quot;<br>                android:value=&quot;androidx.startup&quot; /&gt;<br>        &lt;/provider&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;<br><br>###################################<br><br>#AppContextInitializer.kt<br><br>class AppContextInitializer: Initializer&lt;Context&gt; {<br><br>    companion object {<br>        lateinit var applicationContext: Context<br>    }<br><br>    override fun create(context: Context): Context {<br>        applicationContext = context.applicationContext<br>        return context<br>    }<br><br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;?&gt;?&gt; {<br>        return emptyList()<br>    }<br><br>}</pre><p>Now let’s create Database builder instance</p><pre>#MovieDatabase.kt<br><br>expect fun getDatabaseBuilder(): RoomDatabase.Builder&lt;MovieDatabase&gt;<br><br>###################################<br><br>#MovieDatabase.android.kt<br><br>actual fun getDatabaseBuilder(): RoomDatabase.Builder&lt;MovieDatabase&gt; {<br>    val appContext = AppContextInitializer.applicationContext<br>    val dbFile = appContext.getDatabasePath(&quot;main_db.db&quot;)<br>    return Room.databaseBuilder&lt;MovieDatabase&gt;(<br>        context = appContext,<br>        name = dbFile.absolutePath<br>    )<br>}<br><br>###################################<br><br>#MovieDatabase.ios.kt<br><br>actual fun getDatabaseBuilder(): RoomDatabase.Builder&lt;MovieDatabase&gt; {<br>    val dbFilePath = documentDirectory() + &quot;/main_db.db&quot;<br>    return Room.databaseBuilder&lt;MovieDatabase&gt;(<br>        name = dbFilePath,<br>    )<br>}<br><br>@OptIn(ExperimentalForeignApi::class)<br>private fun documentDirectory(): String {<br>    val documentDirectory = NSFileManager.defaultManager.URLForDirectory(<br>        directory = NSDocumentDirectory,<br>        inDomain = NSUserDomainMask,<br>        appropriateForURL = null,<br>        create = false,<br>        error = null,<br>    )<br>    return requireNotNull(documentDirectory?.path)<br>}</pre><p>That’s it, rest room structure remains the same, no changes in DAO or Entity class.</p><p><strong>Run Android app: </strong>Congrats, Android app now runs fully using <strong>KMP shared module</strong></p><p>Let’s run it on IOS now.</p><h4>Step 5: Create UI and ViewModel alternative for IOS</h4><p>We will first add <em>Skie</em> dependency. <em>Skie</em> library helps between Kotlin and Swift interoperability.</p><p>Skie allows Kotlin Flow → Swift async/await.</p><pre>#libs.version.toml<br><br>skie = &quot;0.10.9&quot;<br><br>[plugins]<br>skie = { id = &quot;co.touchlab.skie&quot;, version.ref = &quot;skie&quot; }<br><br>###################################<br><br>#Project level build.gradle.kts<br><br>alias(libs.plugins.skie) apply false<br><br>###################################<br><br>#Shared Module build.gradle.kts<br><br>alias(libs.plugins.skie)</pre><p>We need to start koin and access movie repository from ios swift files, we will create a mediator class in <em>iosMain</em> folder inside shared module that will do the work, we can directly access it from Swift file</p><pre>#SharedIosInterop.kt<br><br>object SharedIosInterop: KoinComponent {<br><br>    val movieRepository: MovieRepository by inject()<br><br>    fun initKoin() {<br>        startKoin {<br>            modules(sharedModule)<br>        }<br>    }<br>}</pre><p>Let’s create the UI and ViewModel for IOS in iosApp folder. Delete existing Swift file and create the below files.</p><pre>#iosApp.swift<br><br>import SwiftUI<br>import sharedKit<br><br>@main<br>struct iosAppApp: App {<br><br>    private let shared = SharedIosInterop()<br>    // Initialize Koin on app start <br>    init() {<br>        shared.doInitKoin()<br>    }<br><br>    var body: some Scene {<br>        WindowGroup {<br>            MovieScreen(<br>                vm: MovieViewModel(repo: shared.movieRepository)<br>            )<br>        }<br>    }<br>}<br><br>###################################<br><br>#MovieScreen.swift<br><br>struct MovieScreen: View {<br>    @StateObject var vm: MovieViewModel<br><br>    var body: some View {<br>        NavigationStack {<br>            content<br>        }<br>    }<br><br>    @ViewBuilder<br>    private var content: some View {<br>        switch vm.state {<br>        case .loading:<br>            ProgressView()<br><br>        case .failure(let msg):<br>            VStack(spacing: 12) {<br>                Text(msg).multilineTextAlignment(.center)<br>                Button(&quot;Retry&quot;) { vm.start() }<br>            }<br>            .padding()<br><br>        case .success(let movies):<br>            List {<br>                ForEach(movies, id: \.title) { movie in<br>                    NavigationLink {<br>                        DetailScreen(title: movie.title, poster: movie.poster)<br>                    } label: {<br>                        MovieRow(movie: movie)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>struct MovieRow: View {<br>    let movie: MovieData<br><br>    var body: some View {<br>        HStack(spacing: 12) {<br>            AsyncImage(url: URL(string: movie.poster)) { phase in<br>                switch phase {<br>                case .empty:<br>                    Rectangle().opacity(0.2)<br>                case .success(let image):<br>                    image.resizable().scaledToFill()<br>                default:<br>                    Rectangle().opacity(0.2)<br>                }<br>            }<br>            .frame(width: 80, height: 80)<br>            .clipped()<br><br>            Text(movie.title)<br>                .font(.headline)<br><br>            Spacer()<br>        }<br>        .padding(.vertical, 6)<br>    }<br>}<br><br>###################################<br><br>#MovieViewModel.swift<br><br>import Foundation<br>import Combine<br>import sharedKit<br><br>@MainActor<br>final class MovieViewModel: ObservableObject {<br><br>    enum ScreenState {<br>        case loading<br>        case success([MovieData])<br>        case failure(String)<br>    }<br><br>    @Published private(set) var state: ScreenState = .loading<br><br>    private let repo: MovieRepository<br>    private var task: Task&lt;Void, Never&gt;?<br><br>    init(repo: MovieRepository) {<br>        self.repo = repo<br>        start()<br>    }<br><br>    func start() {<br>        task?.cancel()<br>        state = .loading<br><br>        task = Task {<br>            do {<br>                for try await value in repo.getMoviesData() {<br>                    let movies = (value as? [MovieData]) ?? []<br>                    if movies.isEmpty {<br>                        state = .failure(&quot;Empty Data&quot;)<br>                    } else {<br>                        state = .success(movies)<br>                    }<br>                }<br>            } catch {<br>                state = .failure(error.localizedDescription)<br>            }<br>        }<br>    }<br><br>    deinit {<br>        task?.cancel()<br>    }<br>}<br><br>###################################<br><br>#DetailScreen.swift<br><br>import SwiftUI<br><br>struct DetailScreen: View {<br>    let title: String<br>    let poster: String<br><br>    var body: some View {<br>        VStack(spacing: 16) {<br>            Text(title).font(.title2)<br><br>            AsyncImage(url: URL(string: poster)) { phase in<br>                switch phase {<br>                case .empty:<br>                    ProgressView()<br>                case .success(let image):<br>                    image.resizable().scaledToFit()<br>                default:<br>                    Text(&quot;Image load failed&quot;)<br>                }<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><p>We will add few files on .gitignore.</p><pre>#.gitignore<br><br>shared/build<br>xcuserdata<br>*.xcodeproj/*<br>!*.xcodeproj/project.pbxproj<br>!*.xcodeproj/xcshareddata/<br>!*.xcodeproj/project.xcworkspace/<br>!*.xcworkspace/contents.xcworkspacedata<br>**/xcshareddata/WorkspaceSettings.xcsettings</pre><p>Great, now run the IOS project it should run the MVVM app in IOS using shared module</p><p>Finally after all, your structure should look something like this</p><pre>├── app<br>│   ├── src<br>│   │   ├── main<br>│   │   │   ├── java<br>│   │   │   │   └── com.khush.moviesapp<br>│   │   │   │      ├── di.module<br>│   │   │   │      │   └── AppModule.kt<br>│   │   │   │      ├── ui<br>│   │   │   │      │   ├── viewmodel<br>│   │   │   │      │   │   ├── MovieViewModel.kt<br>│   │   │   │      │   │   └── UIState.kt<br>│   │   │   │      │   ├── DetailScreen.kt<br>│   │   │   │      │   ├── MovieActivity.kt<br>│   │   │   │      │   └── MovieScreen.kt<br>│   │   │   │      └── MovieApplication.kt<br>│   │   │   └── AndroidManifest.xml<br>│   ├── build.gradle.kts<br>│   └── proguard-rules.pro<br>├── gradle<br>│   └── libs.versions.toml<br>├── iosApp<br>│   ├── iosApp<br>│   │   ├── DetailScreen.swift<br>│   │   ├── IosApp.swift<br>│   │   ├── MovieScreen.swift<br>│   │   └── MovieViewModel.swift<br>│   └── iosApp.xcodeproj<br>├── shared<br>│   ├── src<br>│   │   ├── androidMain<br>│   │   │   ├── kotlin<br>│   │   │   │   └── com.khush.shared<br>│   │   │   │       └── data<br>│   │   │   │           └── database<br>│   │   │   │              ├── AppContextInitializer.kt<br>│   │   │   │              └── MovieDatabase.android.kt<br>│   │   │   └── AndroidManifest.xml<br>│   │   ├── commonMain<br>│   │   │   └── kotlin<br>│   │   │       └── com.khush.shared<br>│   │   │           ├── data<br>│   │   │           │   ├── database<br>│   │   │           │   │   ├── DatabaseService.kt<br>│   │   │           │   │   ├── MovieDao.kt<br>│   │   │           │   │   ├── MovieDatabase.kt<br>│   │   │           │   │   └── MovieDatabaseService.kt<br>│   │   │           │   ├── model<br>│   │   │           │   │   └── MovieData.kt<br>│   │   │           │   ├── network<br>│   │   │           │   │   └── ApiInterface.kt<br>│   │   │           │   ├── repository<br>│   │   │           │   │   └── MovieRepository.kt<br>│   │   │           │   └── utils<br>│   │   │           │       └── Const.kt<br>│   │   │           └── di<br>│   │   │               └── SharedModule.kt<br>│   │   └── iosMain<br>│   │       └── kotlin<br>│   │           └── com.khush.shared<br>│   │               ├── data<br>│   │               │   └── database<br>│   │               │       └── MovieDatabase.ios.kt<br>│   │               └── interop<br>│   │                   └── SharedIosInterop.kt<br>│   └── build.gradle.kts<br>├── build.gradle.kts<br>└── settings.gradle.kts</pre><h3>Final words</h3><p>Congratulations! Now we are able to run same MVVM app on IOS and it is just the beginning, this base understanding will help you integrate more complex project into IOS later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhYjDAm7AFkvQfyz6RuFTA.png" /></figure><p><strong>Source code (master-multiplatform branch) — </strong><a href="https://github.com/khushpanchal/MultiplatformMoviesApp/tree/master-multiplatform"><strong>Link</strong></a></p><p>Check out the pull request for the conversion for better understanding — <a href="https://github.com/khushpanchal/MultiplatformMoviesApp/pull/1">Link</a></p><p><strong>Contact Me</strong>: <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a>, <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c9e8b148cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your own Android ViewModel from scratch]]></title>
            <link>https://medium.com/@khush.panchal123/create-your-own-android-viewmodel-from-scratch-b29083386e3c?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/b29083386e3c</guid>
            <category><![CDATA[androidviewmodel]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 19:49:52 GMT</pubDate>
            <atom:updated>2026-01-12T19:34:54.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qy1uu5UXTMBieaaqOKmwWg.png" /></figure><p>You have used ViewModel many times, but do you truly know what purpose it serves, how it is created and how it survives rotation?</p><p>In day-to-day Android work, we usually create ViewModels in different ways:</p><ul><li>Directly with ViewModelProvider:</li></ul><pre>val vm = ViewModelProvider(this, factory).get(MyViewModel::class.java)</pre><ul><li>With Hilt (DI)</li></ul><pre>val vm: MyViewModel = hiltViewModel() <br>// Hilt hides the provider way, but internally the idea is still similar</pre><h3>What is the purpose of ViewModel</h3><p>ViewModel is just a class that:</p><ul><li>holds UI state (example loading, failure, success state),</li><li>survives configuration changes (example screen rotation, theme changes),</li><li>gets cleared only when the screen (like activity or fragment) is actually finished</li></ul><p>In this blog, we’ll build a <strong>mini version</strong> of this system ourselves — so the “magic” becomes clear.</p><h3>What we want to achieve</h3><p>Before writing code, let’s define the goals (this keeps the implementation clean):</p><ul><li><strong>ViewModel should survive configuration changes: </strong>ViewModel instance should not be cleared when activity is recreated due to configuration changes like screen rotation.</li><li><strong>Same ViewModel class can exist in multiple Activities, but should not be shared: </strong>Two different Activities can both use SomeViewModel class, but each Activity should have its <strong>own separate instance</strong>.</li><li><strong>One Activity can have multiple ViewModels, but only one instance per ViewModel class: </strong>Inside a single Activity: We can have HomeViewModel, ProfileViewModel, etc.; But for each ViewModel class, there should be <strong>only one instance; </strong>And when the Activity is truly finished (not rotation), <strong>all its ViewModels should be cleared</strong>.</li></ul><h3>Mental model: how we can achieve this</h3><p>Think of the whole system as <strong>two-level storage</strong></p><h4>Level 1: Store ViewModels for an Activity</h4><p>Since a single Activity can have multiple ViewModels, we need a container that can store them all together</p><p>So we create a class called <strong>ViewModelStore</strong> which holds ViewModels in a HashMap:</p><ul><li><strong>key</strong> = canonical(fully qualified including path) name of ViewModel class (e.g,: “com.app.ProfileViewModel”)</li><li><strong>value</strong> = actual ViewModel instance</li></ul><p>That way:</p><ul><li>if Activity asks again for ProfileViewModel, we return the same instance from the map</li><li>if it doesn’t exist, we create and store it</li><li>we can clear it when activity is destroyed by calling clear method on map</li></ul><p>This solves: “single Activity → multiple ViewModels” and “one instance per ViewModel class”.</p><h4>Level 2: Store ViewModelStore outside Activity</h4><p>Now comes the main trick</p><p>If ViewModelStore lives inside Activity, it will die whenever Activity dies.</p><p>But Activity dies in two situations:</p><ol><li><strong>Configuration change</strong> → should NOT clear ViewModels</li><li><strong>Actual finish (back press)</strong> → should clear ViewModels</li></ol><p>So we need to store ViewModelStore <strong>outside Activity</strong> in something that stays alive across rotation</p><p>The simplest “lives-through-the-app” place is the <strong>Application class</strong>.</p><p>So inside Application, we keep another HashMap:</p><ul><li><strong>key</strong> = canonical name of Activity class (example: “com.app.ProfileActivity”)</li><li><strong>value</strong> = the Activity’s ViewModelStore</li></ul><p>This solves: “do not lose ViewModels on rotation”.</p><p>Let’s dive into some code for creating the core components that will help us create our own ViewModel:</p><h3>Core Components</h3><h4>MyViewModel</h4><p>Base contract for ViewModel class.</p><pre>interface MyViewModel {<br>    // Called before actually destroying the viewmodel instance<br>    fun onCleared() {}<br>}</pre><h4>MyViewModelStore</h4><p>Class that stores multiple ViewModels in a HashMap where the key is the ViewModel’s canonical name and the value is the ViewModel instance.</p><pre>class MyViewModelStore {<br>    private val map = HashMap&lt;String, MyViewModel&gt;()<br>   <br>    fun put(key: String, viewModel: MyViewModel) {<br>        val oldViewModel = map.get(key)<br>        oldViewModel?.onCleared()<br>        map[key] = viewModel<br>    }<br>   <br>    fun get(key: String): MyViewModel? {<br>        return map[key]<br>    }<br>   <br>    fun clear() {<br>        for (vm in map.values) {<br>            vm.onCleared()<br>        }<br>        map.clear()<br>    }<br>}</pre><h4>MyViewModelStoreOwner</h4><p>The owner contract. Our Activity will implement this so it can provide the correct MyViewModelStore.</p><pre>interface MyViewModelStoreOwner {<br>    fun getMyViewModelStore(): MyViewModelStore<br>}</pre><h4>MyViewModelProvider(+ Factory)</h4><p>The manager. This is the class that returns the same ViewModel instance if it already exists in the store, or creates a new one using the factory when it doesn’t.</p><pre>class MyViewModelProvider(<br>    private val owner: MyViewModelStoreOwner,<br>    private val factory: MyViewModelFactory<br>) {<br>    fun &lt;T : MyViewModel&gt; get(modelClass: KClass&lt;T&gt;): T {<br>        val key = modelClass.qualifiedName!! // canonical name<br>        var viewModel = owner.getMyViewModelStore().get(key)<br>        // we check if viewModel already exists else create new<br>        if (modelClass.isInstance(viewModel)) {<br>            return viewModel as T<br>        } else {<br>            viewModel = factory.create(modelClass)<br>            owner.getMyViewModelStore().put(key, viewModel)<br>        }<br>        return viewModel as T<br>    }<br>    <br>    interface MyViewModelFactory {<br>        fun &lt;T : MyViewModel&gt; create(modelClass: KClass&lt;T&gt;): T<br>    }<br>}</pre><p>Let’s dive into the some practical example:</p><h3>Counter Example</h3><p>To make this system easy to understand, we’ll use a simple UI: a counter text and a button. The counter value is our “UI state”, and the whole purpose of this demo is to prove:</p><ul><li>Tap the button → count increases</li><li>Rotate the screen → count should stay the same</li><li>Press back / close the Activity → ViewModel should clear.</li></ul><h4>CounterApplication</h4><p>Application class that will be holding the ViewModelStore in HashMap where key will be the canonical name of our ViewModelStoreOwner (like activity).</p><pre>class CounterApplication: Application() {<br>    private val viewModelStores = HashMap&lt;String, MyViewModelStore&gt;()<br>   <br>    fun getViewModelStore(key: String): MyViewModelStore {<br>        return viewModelStores.getOrPut(key) { MyViewModelStore() }<br>    }<br><br>    fun clearViewModelStore(key: String) {<br>        viewModelStores.get(key)?.clear()<br>        viewModelStores.remove(key)<br>    }<br>}</pre><h4>CounterViewModel</h4><p>It holds the count state.</p><pre>class CounterViewModel : MyViewModel {<br>    private var count = 0<br><br>    init {<br>        Log.i(&quot;CounterViewModel&quot;, &quot;ViewModel created&quot;)<br>    }<br><br>    fun getCount(): Int {<br>        return count<br>    }<br><br>    fun incrementCount() {<br>        count++<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        Log.i(&quot;CounterViewModel&quot;, &quot;ViewModel cleared&quot;)<br>    }<br>}</pre><h4>CounterViewModelFactory</h4><p>This will create the ViewModel.</p><pre>class CounterViewModelFactory: MyViewModelProvider.MyViewModelFactory {<br>    override fun &lt;T : MyViewModel&gt; create(modelClass: KClass&lt;T&gt;): T {<br>        return CounterViewModel() as T<br>    }<br>}</pre><h4>CounterActivity</h4><ul><li>Implements MyViewModelStoreOwner that provides ViewModelStore.</li><li>Requests the ViewModel through MyViewModelProvider, uses it to render the UI, and clears everything only when the Activity is actually finished (not on configuration changes).</li></ul><pre>class CounterActivity : AppCompatActivity(), MyViewModelStoreOwner {<br><br>    private lateinit var counterTv: TextView<br>    private lateinit var counterIncreaseBtn: Button<br><br>    private val viewModel: CounterViewModel by lazy {<br>        MyViewModelProvider(this, CounterViewModelFactory()).get(CounterViewModel::class)<br>    }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_counter)<br>        counterTv = findViewById(R.id.textView)<br>        counterIncreaseBtn = findViewById(R.id.button)<br><br>        counterTv.text = viewModel.getCount().toString()<br><br>        counterIncreaseBtn.setOnClickListener {<br>            viewModel.incrementCount()<br>            counterTv.text = viewModel.getCount().toString()<br>        }<br><br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        // check if activity is destroying due to configuration changes<br>        if (!isChangingConfigurations) {<br>            (application as CounterApplication).clearViewModelStore(this.javaClass.canonicalName!!)<br>        }<br>    }<br><br>    override fun getMyViewModelStore(): MyViewModelStore {<br>        return (application as CounterApplication).getViewModelStore(this@CounterActivity.javaClass.canonicalName!!)<br>    }<br>}</pre><h3>Putting it all together (the full picture)</h3><p>Now our brain can imagine the flow like this:</p><ol><li><strong>Activity = ViewModelStoreOwner </strong>(as it owns ViewModelStore)</li></ol><ul><li>It doesn’t create ViewModels directly</li><li>It only knows how to provide its ViewModelStore</li></ul><p><strong>2. Application = the long-living storage</strong></p><ul><li>It keeps one ViewModelStore per Activity class</li><li>Rotation happens → Activity recreates → Application still has the store → ViewModels survive</li></ul><p>3. <strong>ViewModelStore (as it store ViewModels) = the per-Activity container</strong></p><ul><li>It keeps one ViewModel instance per ViewModel class using a map</li></ul><p>4. <strong>ViewModelProvider = the manager</strong></p><ul><li>The provider is the class that “glues everything”</li><li>It checks if ViewModel exists in the store; if yes → returns it; if no → creates it using a <strong>Factory</strong>, stores it, and returns it</li></ul><p><strong>5. Factory = the creator</strong></p><ul><li>Only job: create ViewModels when Provider needs a new one.</li></ul><blockquote><strong>Application holds Activity’s ViewModelStore, and ViewModelStore holds Activity’s ViewModels.</strong></blockquote><blockquote>Two hashmaps → two levels</blockquote><p>And this is how the “magic” works :)</p><h3>Bonus: SavedStateHandle</h3><p>Our current custom ViewModel already survives <strong>rotation</strong>, because the store lives outside the Activity.</p><p>But it still <strong>won’t survive process death</strong> (when Android kills your app in the background to reclaim memory). In that case, the Application memory is gone too — so your stored ViewModel instances are gone as well.</p><p>That’s where <strong>SavedStateHandle</strong> helps:</p><ul><li>Think of it as a small <strong>key–value storage</strong> attached to a ViewModel.</li><li>Android can <strong>save it into a Bundle</strong> and <strong>restore it later</strong>, even after process death.</li></ul><p><strong>Out of scope for this article:</strong> we won’t build a custom SavedStateHandle implementation here.</p><p>But the idea is simple: use onSaveInstanceState(…) to store the important key–values, restore them when the screen comes back, and pass that restored state into your ViewModelFactory, which then passes it into the ViewModel.</p><p><strong>Source Code:</strong> <a href="https://github.com/khushpanchal/HappyCoding/tree/master/MyViewModel/app/src/main/java/com/example/myviewmodel">GitHub</a></p><p><strong>Contact Me:</strong> <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a> | <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b29083386e3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supporting Multiple Languages in Your Android Application]]></title>
            <link>https://medium.com/@khush.panchal123/supporting-multiple-languages-in-your-android-application-a08e21b1baf1?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/a08e21b1baf1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[multilingual]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 18:00:33 GMT</pubDate>
            <atom:updated>2025-01-28T18:00:33.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7fLKNSHKth1cOg0RniJTg.jpeg" /></figure><p>In this blog, we will explore how to implement multilingual support in an Android application providing step-by-step implementation with code snippets.</p><h4>What is Locale?</h4><p>Before diving into the code, let’s understand the term “Locale.”</p><p>A Locale represents a specific geographical, or cultural region. It is used to customize the app’s content, such as language, date formats, currency, etc., to match the user’s preferences. For example: Locale for English: en, Locale for Hindi: hi, Locale for French: fr</p><p>By setting the appropriate Locale in your app, we can ensure that users experience the application in their preferred language.</p><p>Here’s what we aim to achieve:</p><ol><li>Allow users to select their preferred language.</li><li>Save the selected language preference.</li><li>Apply the selected language throughout the app.</li></ol><h3>Step 1: Setting Up the Language Manager</h3><p>We will create a LanguageManager object to handle saving, retrieving, and applying the selected language.</p><pre>object LanguageManager {<br>    private const val LANGUAGE_KEY = &quot;language_key&quot;<br>    private const val DEFAULT_LANGUAGE = &quot;en&quot;<br><br>    fun saveLanguage(context: Context, language: String) {<br>        val sharedPreferences = context.getSharedPreferences(&quot;app_prefs&quot;, Context.MODE_PRIVATE)<br>        sharedPreferences.edit().putString(LANGUAGE_KEY, language).apply()<br>    }<br><br>    fun getLanguage(context: Context): String {<br>        val sharedPreferences = context.getSharedPreferences(&quot;app_prefs&quot;, Context.MODE_PRIVATE)<br>        return sharedPreferences.getString(LANGUAGE_KEY, DEFAULT_LANGUAGE) ?: DEFAULT_LANGUAGE<br>    }<br><br>    fun setLocale(context: Context, language: String): Context {<br>        val locale = Locale(language)<br>        Locale.setDefault(locale)<br>        val config = Configuration(context.resources.configuration)<br>        config.setLocale(locale)<br>        return context.createConfigurationContext(config)<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>saveLanguage()</strong>: Saves the selected language to SharedPreferences so it persists across app restarts.</li><li><strong>getLanguage()</strong>: Retrieves the saved language, defaulting to English (en) if none is set.</li><li><strong>setLocale()</strong>: Updates the app’s Locale to reflect the selected language and ensures the app’s resources are reloaded accordingly. This function is responsible for setting the Locale for the context, ensuring that any resource fetched from the context is based on the updated Locale.</li></ul><h3>Step 2: Updating the Base Context</h3><p>To ensure the selected language is applied throughout the app, we override the attachBaseContext method in a BaseActivity class. All other activities will inherit from this base class.</p><pre>abstract class BaseActivity : ComponentActivity() {<br>    override fun attachBaseContext(newBase: Context) {<br>        val language = LanguageManager.getLanguage(newBase)<br>        val context = LanguageManager.setLocale(newBase, language)<br>        super.attachBaseContext(context)<br>    }<br>}</pre><h4>How It Works:</h4><ul><li>When an activity is created, the attachBaseContext method is called (before onCreate).</li><li>We fetch the saved language using LanguageManager.getLanguage().</li><li>We then apply the saved language by calling LanguageManager.setLocale().</li><li>The updated context ensures that the selected language is used for all resources.</li></ul><h3>Step 3: Creating the Sample Screen</h3><p>We create the MainActivity class inherits from BaseActivity. It serves as the entry point of our app and provides users with the option to select a language.</p><pre>class MainActivity : BaseActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            MultiLanguageTheme {<br>                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -&gt;<br>                    MainScreen(<br>                        modifier = Modifier.padding(innerPadding)<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>The MainScreen composable provides a simple UI for users to select their preferred language.</p><pre>@Composable<br>fun MainScreen(<br>    modifier: Modifier = Modifier,<br>) {<br>    val context = LocalContext.current<br>    Column(<br>        modifier = modifier<br>            .fillMaxSize()<br>            .padding(16.dp),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        // Welcome Text<br>        Text(<br>            text = context.resources.getString(R.string.welcome_text),<br>            modifier = Modifier.padding(bottom = 16.dp)<br>        )<br>        // Language Selection<br>        Text(<br>            text = context.resources.getString(R.string.select_language),<br>            modifier = Modifier.padding(bottom = 8.dp)<br>        )<br>        Row(<br>            modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.SpaceEvenly<br>        ) {<br>            Column(<br>                horizontalAlignment = Alignment.CenterHorizontally,<br>                verticalArrangement = Arrangement.SpaceEvenly<br>            ) {<br>                Button(onClick = { changeLocale(context, &quot;en&quot;) }) {<br>                    Text(text = &quot;English&quot;)<br>                }<br>                Button(onClick = { changeLocale(context, &quot;hi&quot;) }) {<br>                    Text(text = &quot;हिंदी&quot;)<br>                }<br>            }<br>            Column(<br>                horizontalAlignment = Alignment.CenterHorizontally,<br>                verticalArrangement = Arrangement.SpaceEvenly<br>            ) {<br>                Button(onClick = { changeLocale(context, &quot;fr&quot;) }) {<br>                    Text(text = &quot;Français&quot;)<br>                }<br>                Button(onClick = { changeLocale(context, &quot;es&quot;) }) {<br>                    Text(text = &quot;Español&quot;)<br>                }<br>            }<br>        }<br>        // Flag Image<br>        Image(<br>            painter = painterResource(id = R.drawable.flag),<br>            contentDescription = null,<br>            modifier = Modifier<br>                .padding(top = 32.dp)<br>                .size(200.dp)<br>        )<br>    }<br>}</pre><h3>Step 4: Changing the Language Dynamically</h3><p>When a user selects a language, we need to update the Locale and restart the app.</p><pre>fun changeLocale(context: Context, language: String) {<br>    LanguageManager.saveLanguage(context, language)<br>    LanguageManager.setLocale(context, language)<br>    restartApp(context)<br>}<br><br>fun restartApp(context: Context) {<br>    val intent = Intent(context, MainActivity::class.java)<br>    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)<br>    context.startActivity(intent)<br>    if (context is Activity) {<br>        context.finish()<br>    }<br>}</pre><h3>Step 5: Adding Language Resources</h3><p>To support multiple languages, create separate values folders for each language in the res directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*h_0kHZOj8nxGQS5lH3Sxww.png" /></figure><ul><li>res/values/strings.xml (default English):</li></ul><pre>&lt;resources&gt;<br>    &lt;string name=&quot;app_name&quot;&gt;MultiLanguage&lt;/string&gt;<br>    &lt;string name=&quot;welcome_text&quot;&gt;Welcome to the MultiLingual App!&lt;/string&gt;<br>    &lt;string name=&quot;select_language&quot;&gt;Select Language:&lt;/string&gt;<br>&lt;/resources&gt;</pre><ul><li>res/values-hi/strings.xml (Hindi):</li></ul><pre>&lt;resources&gt;<br>    &lt;string name=&quot;app_name&quot;&gt;MultiLanguage&lt;/string&gt;<br>    &lt;string name=&quot;welcome_text&quot;&gt;मल्टीलिंगुअल ऐप में आपका स्वागत है!&lt;/string&gt;<br>    &lt;string name=&quot;select_language&quot;&gt;भाषा चुने:&lt;/string&gt;<br>&lt;/resources&gt;</pre><ul><li>Similarly for other language as well, res/values-fr/strings.xml (French), res/values-es/strings.xml (Spanish)</li><li>For changing images based on locale, similar to values folder, create drawable folder for each language like drawable, drawable-hi, drawable-fr, drawable-es and add the image with the same name in all the folder.</li></ul><h3>Sample app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*m1-i8BIAfCafgMgSgJT2ww.gif" /></figure><p><strong>Source Code:</strong> <a href="https://github.com/khushpanchal/HappyCoding/tree/master/MultiLanguage">GitHub</a></p><p><strong>Contact Me:</strong> <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a> | <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a08e21b1baf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Generics Simplified]]></title>
            <link>https://medium.com/@khush.panchal123/kotlin-generics-simplified-a26ccc9598c0?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26ccc9598c0</guid>
            <category><![CDATA[kotlin-generics]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 18:42:07 GMT</pubDate>
            <atom:updated>2025-01-14T19:01:08.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*3WOa4-8IAgaBZFeBm7E5bw.jpeg" /></figure><p>Generics in Kotlin allow us to write flexible and reusable code. In this article, we’ll dive into the world of Kotlin Generics and cover the following topics:</p><ul><li>What are Generics and Why Do We Need Them?</li><li>Generic Functions</li><li>Constraints in Generics</li><li>Type Erasure in Generics</li><li>Variance in Generics</li></ul><h3>What are Generics and Why Do We Need Them?</h3><p>Generics enable us to write a single class, function, or property that can handle different types. This reduces code duplication and increases flexibility.</p><p>Imagine we’re building an app where users answer questions. We start with a simple Question class:</p><pre>data class Question(<br>    val questionText: String,<br>    val answer: String<br>)<br><br>fun main() {<br>    val question = Question(&quot;Name your favorite programming language&quot;, &quot;Kotlin&quot;)<br>}</pre><p>This works fine for text answers. But what if the answer can also be a number or a boolean? We’d need multiple versions of the Question class or sacrifice type safety by using Any. Both approaches are less than ideal.</p><p><strong>Solution: Generics</strong></p><p>Generics allow us to make the Question class type-flexible by introducing a type parameter &lt;T&gt;:</p><pre>data class Question&lt;T&gt;(<br>    val questionText: String,<br>    val answer: T<br>)<br><br>fun main() {<br>    val questionString = Question(&quot;What&#39;s your favorite programming language?&quot;, &quot;Kotlin&quot;)<br>    val questionBoolean = Question(&quot;Kotlin is statically typed?&quot;, true)<br>    val questionInt = Question(&quot;How many days are in a week?&quot;, 7)<br>}</pre><p>Here, &lt;T&gt; is a placeholder for the type of answer. The compiler ensures type safety while providing flexibility. If needed, you can explicitly specify the type:</p><pre>val questionInt = Question&lt;Int&gt;(&quot;2 + 2 equals?&quot;, 4)</pre><p><strong>Why Use Generics?</strong></p><ul><li>Avoid code duplication.</li><li>Increase reusability.</li><li>Maintain type safety.</li></ul><h3>Generic Functions</h3><p>Generics aren’t just for classes — they work with functions too! To define a generic function, place the type parameter &lt;T&gt; before the function name.</p><pre>fun &lt;T&gt; printValue(value: T) {<br>    println(value)<br>}<br><br>fun &lt;T&gt; T.toCustomString(): String { // Generic extension function<br>    return &quot;Value: $this&quot;<br>}<br><br>fun main() {<br>    printValue(&quot;Hello, Kotlin!&quot;)<br>    printValue(42)<br>    println(3.14.toCustomString())<br>}</pre><h3>Generics Constraints</h3><p>Sometimes, we need the type parameter to meet certain requirements. Constraints restrict the types that can be used as arguments for generics.</p><pre>interface Movable {<br>    fun move()<br>}<br><br>class Car(private val make: String, private val model: String) : Movable {<br>    override fun move() {<br>        println(&quot;$make $model is moving.&quot;)<br>    }<br>}<br><br>fun &lt;T : Movable&gt; run(vehicle: T) {<br>    vehicle.move()<br>}<br><br>fun main() {<br>    run(Car(&quot;BMW&quot;, &quot;X3 M&quot;))<br>}</pre><p>Here, the &lt;T : Movable&gt; constraint ensures that only types implementing Movable can be used. The type specified after a colon is the <strong>upper bound </strong>(Movable).</p><p>The default upper bound (if there was none specified) is Any?</p><p>Only one upper bound can be specified inside the angle brackets. If the same type parameter needs more than one upper bound, we need a separate <strong>where</strong>-clause:</p><pre>interface Flyable {<br>    fun fly()<br>}<br><br>class Plane(private val make: String, private val model: String) : Movable, Flyable {<br>    override fun move() {<br>        println(&quot;$make $model is moving.&quot;)<br>    }<br><br>    override fun fly() {<br>        println(&quot;$make $model is flying.&quot;)<br>    }<br>}<br><br>fun &lt;T&gt; operate(vehicle: T) where T : Movable, T : Flyable {<br>    vehicle.move()<br>    vehicle.fly()<br>}<br><br>fun main() {<br>    operate(Plane(&quot;Boeing&quot;, &quot;747&quot;))<br>}</pre><p>The where clause ensures that the type T satisfies multiple constraints.</p><h3>Type Erasure in Generics</h3><p>At compile time, the compiler removes the type argument from the function call. This is called <strong>type erasure</strong>. The reified keyword retains the type information at runtime, but it can only be used in inline functions. Reified let us use reflection on type parameter. Function must be inline to use reified.</p><pre>// Generics reified<br>fun &lt;T&gt; printSomething(value: T) {<br>    println(value.toString())// OK<br>//    println(&quot;Doing something with type: ${T::class.simpleName}&quot;) // Error<br>}<br><br>inline fun &lt;reified T&gt; doSomething(value: T) {<br>    println(&quot;Doing something with type: ${T::class.simpleName}&quot;) // OK<br>}</pre><h3>Variance in Generics</h3><p>Variance modifiers out and in help make generics flexible by controlling how subtypes are treated. Kotlin offers three variance:</p><ol><li><strong>Invariant (</strong>T<strong>)</strong></li><li><strong>Covariant (</strong>out T<strong>)</strong></li><li><strong>Contravariant (</strong>in T<strong>)</strong></li></ol><h4><strong>Invariant Generics</strong></h4><p>By default, Kotlin generics are invariant. This means that even if B is a subclass of A, Container&lt;B&gt; is not a subclass of Container&lt;A&gt;.</p><pre>class Container&lt;T&gt;(val item: T)<br><br>fun main() {<br>    val intContainer = Container(10)<br>    // val numberContainer: Container&lt;Number&gt; = intContainer // Error: Type mismatch<br>}</pre><p>Invariant generics ensure that no unsafe operations occur, as Container&lt;T&gt; guarantees the exact type of T.</p><h4><strong>Covariant Generics (</strong><strong>out T)</strong></h4><p>The out modifier is used when a generic class or function only <strong>produces</strong> values of type T. It ensures that subtypes are preserved, meaning if Dog is a subtype of Animal, then Producer&lt;Dog&gt; is also a subtype of Producer&lt;Animal&gt;.</p><pre>open class Animal<br>class Dog : Animal()<br><br>class AnimalProducer&lt;out T&gt;(private val instance: T) {<br>    fun produce(): T = instance<br>    // fun consume(value: T) { /* ... */ } // This will show compile time error<br>}<br><br>fun main() {<br>    val dogProducer: AnimalProducer&lt;Animal&gt; = AnimalProducer(Dog())<br>    println(&quot;Produced: ${dogProducer.produce()}&quot;) // Works because of `out`<br>}</pre><h4><strong>Contravariant</strong> Generics (in T)</h4><p>The in modifier is used when a generic class or function only <strong>consumes</strong> values of type T. It reverses the subtyping relationship. If Dog is a subtype of Animal, then Consumer&lt;Animal&gt; is a subtype of Consumer&lt;Dog&gt;.</p><pre>class AnimalConsumer&lt;in T&gt; {<br>    fun consume(value: T) {<br>        println(&quot;Consumed: ${value.toString()}&quot;)<br>    }<br>    // fun produce(): T { /* ... */ } //This will show compile time error<br>}<br><br>fun main() {<br>    val animalConsumer: AnimalConsumer&lt;Dog&gt; = AnimalConsumer&lt;Animal&gt;()<br>    animalConsumer.consume(Dog()) // Works because of `in`<br>}</pre><p><strong>Source Code:</strong> <a href="https://github.com/khushpanchal/HappyCoding/blob/master/app/src/main/java/com/khush/happycoding/kotlin/generics/Generics.kt">GitHub</a></p><p><strong>Contact Me:</strong> <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a> | <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26ccc9598c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create and Publish an Android Library for Beginners]]></title>
            <link>https://medium.com/@khush.panchal123/how-to-create-and-publish-an-android-library-for-beginners-b049c4322255?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/b049c4322255</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jitpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 04:14:31 GMT</pubDate>
            <atom:updated>2025-01-11T08:26:50.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pp1rc8r4Hww3yPcaayfSbA.png" /></figure><p>In this article, we will explore the simplest way to create and publish an open-source Android library. This guide is divided into three parts:</p><ol><li>How to push an Android project to GitHub</li><li>How to create an Android Library</li><li>How to publish the library</li></ol><h4>Create and Push the Project to GitHub</h4><p>For demonstration, we’ll create a basic library to show a toast (short UI message).</p><ul><li>Open Android Studio and create a new project with an empty activity. Set the project name (e.g., ToastMe) and package name (e.g., com.toastme), then click <strong>Finish</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRE2yPO7_UgQdgSaNcIrmw.png" /></figure><ul><li>Go to GitHub and create a new repository (e.g., ToastMe).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcMP7nm0NnFAD7DHFcPh-Q.png" /></figure><ul><li>Open the Android Studio terminal and run the following commands:</li></ul><pre>git init<br>git remote add origin git@github.com:khushpanchal/ToastMe.git<br>git add .<br>git commit -m &quot;Init commit&quot;<br>git push -u origin main</pre><ul><li>Refresh GitHub to confirm the code has been pushed.</li></ul><h4>Create an Android Library</h4><p>Now, let’s create the library module.</p><ul><li>In Android Studio, go to <strong>File &gt; New &gt; New Module</strong>.</li><li>Select <strong>Android Library</strong>, set a name (e.g., toastlibrary), and package name (e.g., com.toastlibrary), then click <strong>Finish</strong>.</li><li>You should see a new folder (toastlibrary) in the project structure.</li><li>Add a ToastUtil class in the library module with a utility function to show a toast message:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Rpaxgri1RSHQoWA3jNcOg.png" /></figure><ul><li>Commit the changes:</li></ul><pre>git add .<br>git commit -m &quot;Add toastlibrary module&quot;<br>git push</pre><ul><li>To test the library, add the following dependency to the app-level build.gradle:</li></ul><pre>implementation(project(&quot;:toastlibrary&quot;))</pre><p>Now, ToastUtil can be used anywhere in the app.</p><h4>Publish the library</h4><p>Now comes the interesting part, let’s publish it and make it open source for world to use. We will be using <a href="http://jitpack.io/">JitPack</a> for hosting our library.</p><ul><li>Add the maven-publish plugin to the project-level build.gradle.kts:</li></ul><pre>plugins {<br>    alias(libs.plugins.android.application) apply false<br>    alias(libs.plugins.kotlin.android) apply false<br>    alias(libs.plugins.android.library) apply false<br>    `maven-publish` // Add this<br>}</pre><ul><li>Update the library (toastlibrary) module’s build.gradle.kts:</li></ul><pre>plugins {<br>    alias(libs.plugins.android.library)<br>    alias(libs.plugins.kotlin.android)<br>    `maven-publish` // Add this<br>}<br><br>android {<br>    ..<br>    ..<br>    publishing { // Add this<br>        singleVariant(&quot;release&quot;) {<br>            withSourcesJar()<br>            withJavadocJar()<br>        }<br>    }<br>}<br><br>dependencies {<br>    ..<br>    ..<br>}<br><br>// Add this<br>publishing {<br>    publications {<br>        create(&quot;release&quot;, MavenPublication::class) {<br>            groupId = &quot;com.github.khushpanchal&quot; // com.github.&lt;yourusername&gt;<br>            artifactId = &quot;ToastMe&quot; // your repository name<br>            version = &quot;0.0.1&quot; // version we want to publish (say 0.0.1)<br><br>            afterEvaluate {<br>                from(components[&quot;release&quot;])<br>            }<br>        }<br>    }<br>}</pre><ul><li>Create jitpack.yml file at project root level and add following</li></ul><pre>jdk:<br>  - openjdk17</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PChAlDWbxBMGVvauPzhLsg.png" /></figure><ul><li>Go to GitHub and create a new release:<br>- Navigate to the <strong>Releases</strong> tab in the right and click <strong>Create a new release</strong>.<br>- Choose a tag (e.g., 0.0.1), add a title (e.g., v0.0.1), and publish the release.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMqfkgeC92j_Gqn8gVscwQ.png" /></figure><ul><li>Go to <a href="https://jitpack.io/">JitPack.io</a>, log in with GitHub, and enter the repository URL (e.g., khushpanchal/ToastMe). Click <strong>Get It</strong> and wait for the build to complete.</li><li>Once published, the library will be available for use.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkwm7Kny8SgzFenrPGZYYA.png" /></figure><h4>Test the Published Library</h4><ul><li>Add JitPack to the settings.gradle.kts of any Android project:</li></ul><pre>dependencyResolutionManagement {<br>    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)<br>    repositories {<br>        google()<br>        mavenCentral()<br>        maven {<br>            url = uri(&quot;https://jitpack.io&quot;) // this one<br>        }<br>    }<br>}</pre><ul><li>Add the library to the module-level build.gradle.kts:</li></ul><pre>implementation(&quot;com.github.khushpanchal:ToastMe:0.0.1&quot;)</pre><h4>Conclusion</h4><p>Congratulations! You have successfully created and published your first Android library. To update the library, modify the code, push the changes to GitHub, create a new release tag, and let JitPack handle the rest.</p><p><strong>Source Code:</strong> <a href="https://github.com/khushpanchal/ToastMe">GitHub</a></p><p><strong>Contact Me:</strong> <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a> | <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b049c4322255" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by Step guide to create basic MVVM Application in Android]]></title>
            <link>https://medium.com/@khush.panchal123/step-by-step-guide-to-create-basic-mvvm-application-in-android-4c1bd83ac628?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c1bd83ac628</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 04:30:09 GMT</pubDate>
            <atom:updated>2024-10-11T06:47:51.853Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Machine Coding LLD Android — MVVM-Hilt-Retrofit</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pzIen2sV6noyt1hB" /></figure><p>In this blog we will create a basic mvvm application where user will fetch some data from the api and show it to the UI as a list.</p><p>For the sake of this article, we will use OMDb (The Open Movie Database) API to fetch the title and thumbnail image of the movie.</p><p>Purpose of this blog is to get started with creating MVVM project following proper architecture which can be used as a base to create any project.</p><blockquote>This blog will help in machine coding round in android interviews.</blockquote><p>Out of Scope for this blog:</p><ul><li>Pagination</li><li>Testing</li><li>Compose</li><li>Offline Caching</li><li>Multiple Screen / Search section</li></ul><blockquote>Check out the <a href="https://github.com/khushpanchal/NewsApp">NewsApp</a> that covers all the above out of scope points.</blockquote><h4>1. Understanding the API</h4><ul><li>For this article we will be using free open source movie api which can be found at: <a href="https://www.omdbapi.com/?s=army&amp;apikey=[yourkey]">https://www.omdbapi.com?s=army&amp;apikey=[yourkey]</a> (To Get Free API Key go to <a href="https://www.omdbapi.com/">https://www.omdbapi.com/</a> and then API Key tab) ( I have used the search “army” keyword for the sake of this article so we can get some list of data)</li><li>Json looks like this:</li></ul><pre>{<br>  &quot;Search&quot;: [<br>    {<br>      &quot;Title&quot;: &quot;Hellboy II: The Golden Army&quot;,<br>      &quot;Year&quot;: &quot;2008&quot;,<br>      &quot;imdbID&quot;: &quot;tt0411477&quot;,<br>      &quot;Type&quot;: &quot;movie&quot;,<br>      &quot;Poster&quot;: &quot;https://m.media-amazon.com/images/M/MV5BMjA5NzgyMjc2Nl5BMl5BanBnXkFtZTcwOTU3MDI3MQ@@._V1_SX300.jpg&quot;<br>    },<br>    {<br>      &quot;Title&quot;: &quot;Army of Darkness&quot;,<br>      &quot;Year&quot;: &quot;1992&quot;,<br>      &quot;imdbID&quot;: &quot;tt0106308&quot;,<br>      &quot;Type&quot;: &quot;movie&quot;,<br>      &quot;Poster&quot;: &quot;https://m.media-amazon.com/images/M/MV5BODcyYzM4YTAtNGM5MS00NjU4LTk2Y2ItZjI5NjkzZTk0MmQ1XkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg&quot;<br>    }, <br>    ..<br>    ..<br>   ],<br>  &quot;totalResults&quot;: &quot;703&quot;,<br>  &quot;Response&quot;: &quot;True&quot;<br>}</pre><ul><li>For this project we show the list showing image and title of the movie.</li></ul><h4>2. Add dependencies</h4><ul><li>Create the new android project in Android Studio and add the following dependency in <strong>app</strong> level build.gradle.kts or build.gradle file.</li></ul><pre>//build.gradle.kts<br><br>dependencies {<br>    <br>    //Dagger for dependency injection<br>    implementation(&quot;com.google.dagger:hilt-android:2.51&quot;)<br>    kapt(&quot;com.google.dagger:hilt-compiler:2.51&quot;)<br><br>    //Glide for image loading<br>    implementation(&quot;com.github.bumptech.glide:glide:4.16.0&quot;)<br><br>    //Retrofit for networking<br>    implementation(&quot;com.squareup.retrofit2:retrofit:2.9.0&quot;)<br>    implementation(&quot;com.squareup.retrofit2:converter-gson:2.9.0&quot;)<br><br>    //ViewModel scope<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.2&quot;)<br>}</pre><ul><li>Additionally for Hilt add the following plugins in <strong>app</strong> level build.gradle.kts or build.gradle file.</li></ul><pre>//build.gradle.kts<br><br>plugins {<br>    id(&quot;com.android.application&quot;)<br>    id(&quot;org.jetbrains.kotlin.android&quot;)<br>    id(&quot;kotlin-kapt&quot;) //&lt;-- this one<br>    id(&quot;com.google.dagger.hilt.android&quot;) // &lt;-- this one<br>}</pre><ul><li>Also add following at <strong>root</strong> level build.gradle.kts or build.gradle file.</li></ul><pre>//build.gradle.kts<br><br>plugins {<br>    id(&quot;com.android.application&quot;) version &quot;8.1.4&quot; apply false<br>    id(&quot;org.jetbrains.kotlin.android&quot;) version &quot;1.9.0&quot; apply false<br>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.51&quot; apply false //&lt;-- this one<br>}</pre><ul><li>Since we will be using view binding for our xml layouts, add the following in <strong>app</strong> level build.gradle.kts or build.gradle file.</li></ul><pre>//build.gradle.kts<br><br>android {<br>..<br>..<br>  buildFeatures {<br>      viewBinding = true<br>  }<br>}</pre><ul><li>Sync the gradle and run your project.</li></ul><h4>3. Create Application class and Add necessary permissions in Manifest file</h4><ul><li>Create Application class and add @HiltAndroidApp annotation.</li></ul><pre>//MainApplication.kt<br><br>@HiltAndroidApp<br>class MainApplication: Application()</pre><ul><li>Add the name in manifest file.</li></ul><pre>&lt;!--AndroidManifest.xml--&gt;<br><br>&lt;application<br>  android:name=&quot;.MainApplication&quot;&gt;<br>&lt;/application&gt;</pre><ul><li>Add Internet permission in manifest file.</li></ul><pre>&lt;!--AndroidManifest.xml--&gt;<br><br>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><h4>4. Create Folder structure</h4><ul><li>Create the following folder structure, with empty folders (“common”, “data/model”, “data/network”, “data/repository”, “di/module”, “ui”, “ui/viewmodel”).</li><li>Check the below final project structure added for reference only, we will create each file step by step.</li></ul><pre>|── MainApplication.kt<br>├── common<br>│   ├── Const.kt<br>│   └── UIState.kt<br>├── data<br>│   ├── model<br>│   │   ├── MainData.kt<br>│   ├── network<br>│   │   ├── ApiInterface.kt<br>│   └── repository<br>│       └── MainRepository.kt<br>├── di<br>│   ├── module<br>│   │   └── ApplicationModule.kt<br>├── ui<br>    ├── MainActivity.kt<br>    ├── MainAdapter.kt<br>    └── viewmodel<br>        ├── MainViewModel.kt<br></pre><h4>5. Create Model class (Data Layer)</h4><ul><li>Create class MainData.kt inside “data/model” folder and add the following data class based on the JSON, we are using only title and image.</li></ul><pre>//MainData.kt<br><br>data class ApiResponse(<br>    @SerializedName(&quot;Search&quot;)<br>    val dataList: List&lt;MainData&gt;?<br>)<br><br>data class MainData(<br>    @SerializedName(&quot;Title&quot;)<br>    val title: String,<br><br>    @SerializedName(&quot;Poster&quot;)<br>    val poster: String<br>)</pre><h4>6. Create Networking interface (Data Layer)</h4><ul><li>First create object class Const.kt inside “common” folder and add Base url and Api Key.</li></ul><pre>//Const.kt<br><br>object Const {<br>    const val BASE_URL = &quot;https://www.omdbapi.com/&quot;<br>    const val API_KEY = &quot;your api key&quot;<br>}</pre><ul><li>Then create ApiInterface.kt class inside “data/network” folder with following function.</li></ul><pre>//ApiInterface.kt<br><br>interface ApiInterface {<br>    @GET(&quot;.&quot;)<br>    suspend fun getMoviesData(<br>        @Query(&quot;s&quot;) s: String = &quot;army&quot;,<br>        @Query(&quot;apikey&quot;) apikey: String = Const.API_KEY<br>    ): ApiResponse<br>}</pre><ul><li>We are not using OkHttp interceptor for adding api key for of this article but it is recommended to add api key via interceptors.</li></ul><h4>7. Create ApplicationModule (DI Layer)</h4><ul><li>Create ApplicationModule.kt class inside “di/module” folder for providing Retrofit instance.</li></ul><pre>//ApplicationModule.kt<br><br>@Module<br>@InstallIn(SingletonComponent::class)<br>class ApplicationModule {<br>    <br>    @Singleton<br>    @Provides<br>    fun provideNetworkService(): ApiInterface {<br>        return Retrofit<br>            .Builder()<br>            .baseUrl(Const.BASE_URL)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>            .create(ApiInterface::class.java)<br>    }<br>}</pre><h4>8. Create Repository class (Data Layer)</h4><ul><li>Create MainRepository.kt class inside “data/repository” folder that will return flow of list which will be collected by view model.</li></ul><pre>//MainRepository.kt<br><br>@Singleton<br>class MainRepository @Inject constructor(<br>    private val apiInterface: ApiInterface<br>) {<br><br>    fun getMainData(): Flow&lt;List&lt;MainData&gt;&gt; {<br>        return flow {<br>            emit(<br>                apiInterface.getMoviesData().dataList ?: emptyList()<br>            )<br>        }<br>    }<br>}</pre><h4>9. Create ViewModel and UIState (UI Layer)</h4><ul><li>First create UIState.kt inside “common” folder which is a sealed interface representing the state of UI that will emit and collect between ViewModel and UI component.</li></ul><pre>//UIState.kt<br><br>sealed interface UIState&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : UIState&lt;T&gt;<br>    data class Failure&lt;T&gt;(val throwable: Throwable, val data: T? = null) : UIState&lt;T&gt;<br>    data object Loading : UIState&lt;Nothing&gt;<br>}</pre><ul><li>Then create MainViewModel.kt inside “ui/viewmodel” folder which extends ViewModel() and inject MainRepository.</li><li>We use StateFlow to emit data from ViewModel and then collect by UI.</li><li>We use IO dispatcher for network call (For this article we are not injecting dispatcher from outside, but it is recommended to provide from outside).</li></ul><pre>//MainViewModel.kt<br><br>@HiltViewModel<br>class MainViewModel @Inject constructor(<br>    private val mainRepository: MainRepository<br>) : ViewModel() {<br><br>    private val _mainItem = MutableStateFlow&lt;UIState&lt;List&lt;MainData&gt;&gt;&gt;(UIState.Loading)<br>    val mainItem: StateFlow&lt;UIState&lt;List&lt;MainData&gt;&gt;&gt; = _mainItem<br><br>    init {<br>        fetchItems()<br>    }<br><br>    private fun fetchItems() {<br>        viewModelScope.launch {<br>            _mainItem.emit(UIState.Loading)<br>            mainRepository<br>                .getMainData()<br>                .flowOn(Dispatchers.IO)<br>                .catch {<br>                    _mainItem.emit(UIState.Failure(it))<br>                }<br>                .collect {<br>                    _mainItem.emit(UIState.Success(it))<br>                }<br>        }<br>    }<br><br>}</pre><h4>10. Create Layouts (UI Layer)</h4><ul><li>Edit activity_main.xml with RecyclerView for showing the list, progress bar and error message.</li></ul><pre>&lt;!--activity_main.xml--&gt;<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.ui.MainActivity&quot;&gt;<br><br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/rv&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:visibility=&quot;gone&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;ProgressBar<br>        android:id=&quot;@+id/progress&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:visibility=&quot;gone&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/error&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:visibility=&quot;gone&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        tools:text=&quot;Something went wrong&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><ul><li>Create item_main.xml layout and put inside “res” folder for single item visible on UI that will be used by Recycler View Adapter.</li></ul><pre>&lt;!--item_main.xml--&gt;<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;110dp&quot;&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/iv_item&quot;<br>        android:layout_width=&quot;100dp&quot;<br>        android:layout_height=&quot;100dp&quot;<br>        android:layout_margin=&quot;5dp&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        tools:background=&quot;@color/design_default_color_secondary&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tv_item&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_margin=&quot;5dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@+id/iv_item&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        tools:text=&quot;Hey there&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><h4>11. Create Adapter class (UI Layer)</h4><ul><li>Create MainAdapter.kt inside “ui” folder that extends RecyclerView Adapter.</li><li>We use DiffUtil for calculating data diff and bind data.</li><li>We use Glide for loading image into image view.</li></ul><pre>//MainAdapter.kt<br><br>class MainAdapter : RecyclerView.Adapter&lt;MainAdapter.MainViewHolder&gt;() {<br><br>    private val items = ArrayList&lt;MainData&gt;()<br><br>    fun setItems(items: List&lt;MainData&gt;) {<br>        val diffResult = DiffUtil.calculateDiff(MainDiffCallBack(this.items, items))<br>        this.items.clear()<br>        this.items.addAll(items)<br>        diffResult.dispatchUpdatesTo(this)<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {<br>        return MainViewHolder(<br>            ItemMainBinding.inflate(LayoutInflater.from(parent.context), parent, false)<br>        )<br>    }<br><br>    override fun getItemCount(): Int {<br>        return items.size<br>    }<br><br>    override fun onBindViewHolder(holder: MainViewHolder, position: Int) {<br>        holder.bind(items[position])<br>    }<br><br>    inner class MainViewHolder(private val binding: ItemMainBinding) : ViewHolder(binding.root) {<br><br>        fun bind(mainData: MainData) {<br>            binding.tvItem.text = mainData.title<br>            Glide.with(itemView.context)<br>                .load(mainData.poster)<br>                .placeholder(com.google.android.material.R.color.design_default_color_secondary)<br>                .into(binding.ivItem)<br>        }<br><br>    }<br>}<br><br>class MainDiffCallBack(private val oldList: List&lt;MainData&gt;, private val newList: List&lt;MainData&gt;) :<br>    DiffUtil.Callback() {<br>    override fun getOldListSize(): Int {<br>        return oldList.size<br>    }<br><br>    override fun getNewListSize(): Int {<br>        return newList.size<br>    }<br><br>    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {<br>        return (oldList[oldItemPosition].title == newList[newItemPosition].title)<br><br>    }<br><br>    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {<br>        return oldList[oldItemPosition] == newList[newItemPosition]<br>    }<br>}</pre><h4>12. Observe UIState inside MainActivity (UI Layer)</h4><ul><li>Drag MainActivity.kt file inside “ui” folder.</li><li>We collect Flow from viewmodel and update UI.</li></ul><pre>//MainActivity.kt<br><br>@AndroidEntryPoint<br>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var binding: ActivityMainBinding<br><br>    private lateinit var adapter: MainAdapter<br><br>    private val mainViewModel: MainViewModel by lazy {<br>        ViewModelProvider(this)[MainViewModel::class.java]<br>    }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityMainBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br>        adapter = MainAdapter()<br>        collector()<br>        setupUI()<br>    }<br><br>    private fun setupUI() {<br>        binding.rv.adapter = adapter<br>        binding.rv.layoutManager =<br>            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)<br>        binding.rv.addItemDecoration(<br>            DividerItemDecoration(<br>                this,<br>                DividerItemDecoration.VERTICAL<br>            )<br>        )<br>    }<br><br>    private fun collector() {<br>        lifecycleScope.launch {<br>            repeatOnLifecycle(Lifecycle.State.STARTED) {<br>                mainViewModel.mainItem.collect {<br>                    when (it) {<br>                        is UIState.Success -&gt; {<br>                            binding.progress.visibility = View.GONE<br>                            binding.error.visibility = View.GONE<br>                            binding.rv.visibility = View.VISIBLE<br>                            adapter.setItems(it.data)<br>                        }<br><br>                        is UIState.Failure -&gt; {<br>                            binding.progress.visibility = View.GONE<br>                            binding.error.visibility = View.VISIBLE<br>                            binding.rv.visibility = View.GONE<br>                            binding.error.text = it.throwable.toString()<br>                        }<br><br>                        is UIState.Loading -&gt; {<br>                            binding.progress.visibility = View.VISIBLE<br>                            binding.error.visibility = View.GONE<br>                            binding.rv.visibility = View.GONE<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><blockquote>Run your application after each step to check everything is working fine.</blockquote><h4>High level flow</h4><ul><li>Check the below high level flow of how data coming from API and is shown to UI.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*06nKWKOk5sU5Lxjtu4ivVQ.jpeg" /></figure><ul><li>Using the above step by step approach help making a base for any MVVM application making it scalable.</li></ul><h4>Final Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*aRmc3d35n2kgZvDUoOWvDQ.jpeg" /></figure><p>Source Code: <a href="https://github.com/khushpanchal/MoviesApp/tree/master">GitHub</a></p><h3>Contact Me:</h3><p><a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a>, <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy Coding ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c1bd83ac628" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton: How to create?]]></title>
            <link>https://medium.com/@khush.panchal123/singleton-how-to-create-815b55290d20?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/815b55290d20</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 19:11:16 GMT</pubDate>
            <atom:updated>2024-06-02T19:11:16.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*rXGK9VI4YQghFSK3WGo-uQ.jpeg" /></figure><p>In this article, we will understand the Singleton class, the pros and cons of using Singleton, and finally, the ways of writing a Singleton class in Kotlin.</p><h3>What is Singleton?</h3><p>Singleton is a creational design pattern that ensures a single instance of a class for the lifetime of an application.</p><h4>Pros</h4><ul><li><strong>Global Point of Access</strong>: Makes the Singleton class easy to access.</li><li><strong>Reduced Memory Usage</strong>: Avoids repeated allocation and deallocation of memory, reducing the garbage collector’s overhead.</li></ul><h4>Cons</h4><ul><li><strong>Tight Coupling and Difficult Testing</strong>: Can create dependencies, making the application hard to test and modify.</li><li><strong>Thread Safety and Memory Leaks</strong>: If not handled properly, it can lead to problems with thread safety and memory leaks.</li></ul><h3>Ways to write Singleton:</h3><h4>Double-Checked locking method (Lazy Initialization)</h4><p>In double-checked locking, we check for an existing instance of the Singleton class twice, before and after entering the synchronized block, ensuring that no more than one instance of Singleton gets created.</p><pre>class Singleton private constructor() {<br>  companion object {<br>    @Volatile<br>    private var instance: Singleton? = null<br>    fun getInstance(): Singleton {<br>        if(instance==null) { //Check 1<br>            synchronized(this) {<br>                if(instance==null) {//Check 2<br>                    instance = Singleton()<br>                }<br>            }<br>        }<br>        return instance!!<br>    }<br>  }<br>}</pre><p>Explanation:</p><ul><li><strong>Private constructor</strong>: Ensures that the constructor can only be accessed within the class.</li><li><strong>Synchronized block</strong>: Ensures that only one thread can enter the block at a time, preventing multiple instances from being created.</li><li><strong>Companion object (</strong>can be used without creating instance of a class<strong>)</strong>: Used to create the Singleton class. It contains a static method (getInstance()) which returns the single instance of the class.</li><li><strong>Volatile Keyword</strong>: Ensures that the instance is immediately visible to other threads after creation.</li><li><strong>Check 1</strong>: If we do not add this check, every time getInstance() is called thread(s) have to enter synchronized block which will cause performance overhead by blocking other threads.</li><li><strong>Check 2</strong>: As multiple thread can go in waiting state on synchronized block(but already entered the getInstance() method), if one thread creates the instance and it is visible to all the threads immediately (using volatile), this check will prevent creation of instance again.</li></ul><h4>Object keyword in Kotlin (Eager Initialization)</h4><p>There is one more easy way to create a singleton — <strong>Object</strong>.</p><p>Let’s check the example</p><pre>object Config {<br>  const val TAG = &quot;Config&quot;<br>}</pre><p>Then why do we even need the double-checked locking method?</p><p>Let’s decompile the class to understand how the instance is created internally:</p><pre>public final class Config {<br>   @NotNull<br>   public static final String TAG = &quot;Config&quot;;<br>   @NotNull<br>   public static final Config INSTANCE;<br>  <br>   private Config() {<br>   }<br>  <br>   static {<br>      Config var0 = new Config();<br>      INSTANCE = var0;<br>   }<br>}</pre><p>As we can see, when decompiled, it uses a static block to create the instance. The static block in Java runs as soon as the class is loaded. The JVM internally loads classes lazily, ensuring thread safety.</p><p><strong>Difference between both methods:</strong></p><ul><li><strong>Object Keyword</strong>: Creates the instance as soon as the class is loaded. (<strong>Eager Initialization</strong>).</li><li><strong>Double-Checked Locking</strong>: Creates the instance only when getInstance() is called, even if the class is already loaded (<strong>Lazy Initialization</strong>).</li></ul><p><strong>Which method should we use?</strong></p><p>Both methods work similarly in creating a Singleton and can be used if handled properly.</p><p><strong>Things to consider:</strong></p><ul><li>With the object expression, if the class is loaded by mistake and never used, the instance will still occupy memory throughout the application’s lifecycle.</li></ul><pre>object Config {<br>    const val TAG = &quot;Config&quot;<br>}<br><br>val nameConfig = Config.javaClass.simpleName //instance of Config will be created</pre><ul><li>We cannot pass arguments to object class as it does not have a constructor, but we can when creating it manually.</li></ul><pre>class Singleton private constructor(tag: String) {<br>    ..<br>    fun getInstance(tag: String): Singleton {<br>       ..<br>       if(instance == null) {<br>         instance = Singleton(tag)<br>       }<br>       ..<br>       return instance!!<br>    }<br>}</pre><h4>Bonus: Companion Object</h4><pre>class Demo {<br>    companion object DemoConfig {<br>        const val TAG = &quot;DemoConfig&quot;<br>    }<br>}<br><br>fun main() {<br>    val nameDemo = Demo //instance of DemoConfig will be created, Demo instance will not be created<br>}<br></pre><p>The companion object is equivalent to the static keyword in Java. It is associated with the class and is instantiated as soon as the containing class is loaded, even if the companion object itself is not used. We can use the companion object without instantiating the corresponding class.</p><p>Source Code: <a href="https://github.com/khushpanchal/HappyCoding/blob/master/app/src/main/java/com/khush/happycoding/kotlin/KotlinSingleton.kt">GitHub</a></p><h3>Contact Me:</h3><p><a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a>, <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy Coding ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815b55290d20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kotlin’s Any, Unit, Nothing]]></title>
            <link>https://medium.com/@khush.panchal123/understanding-kotlins-any-unit-nothing-7bcaad73fbc1?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcaad73fbc1</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Mon, 20 May 2024 03:57:35 GMT</pubDate>
            <atom:updated>2024-05-20T04:21:20.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*m7aZ7cCQWVFXaZEyc6V0sw.jpeg" /></figure><p>Kotlin offers unique types that can be quite different from what developers are used to in Java. In this blog, we will explore three such types: <strong>Any</strong>, <strong>Unit</strong>, and <strong>Nothing</strong>.</p><h3>Any</h3><pre>//SOURCE CODE<br>package kotlin<br>/**<br> * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.<br> */<br>public open class Any {<br>    public open operator fun equals(other: Any?): Boolean<br>    public open fun hashCode(): Int<br>    public open fun toString(): String<br>}</pre><ul><li>Root of the class hierarchy. Every Kotlin class inherits from Any.</li><li><strong>Equivalent to </strong><strong>Object in Java.</strong></li><li>Provides three methods that we can override: equals(), hashCode(), and toString(). This is why when we override methods in any class, these three options are often presented by the IDE.</li><li>Non-nullable by Default. If we need a variable to be able to hold null, we can use Any?.</li></ul><p>Example</p><pre>fun printAny(value: Any?) {<br>    println(value.toString())<br>}<br><br>fun main() {<br>    printAny(&quot;Hello, World!&quot;)  // Prints: Hello, World!<br>    printAny(123)  // Prints: 123<br>}</pre><pre>//When decompiled, Any becomes Object in Java<br>public static final void printAny(@Nullable Object value) {<br>   String var1 = String.valueOf(value);<br>   System.out.println(var1);<br>}</pre><h3>Unit</h3><pre>//SOURCE CODE<br>package kotlin<br>/**<br> * The type with only one value: the `Unit` object. This type corresponds to the `void` type in Java.<br> */<br>public object Unit {<br>    override fun toString() = &quot;kotlin.Unit&quot;<br>}</pre><ul><li><strong>Equivalent to </strong><strong>void in Java</strong> but unlike void ,Unit is a real class with only one instance (singleton).</li><li>Represent a function that does not return any meaningful value.</li><li>If we do not specify a return type for a function, Kotlin uses Unit as the default return type.</li></ul><p>Example</p><pre>fun printMessage(message: String): Unit { //There is no need to explicitly write Unit<br>    println(message)<br>}<br><br>fun main() {<br>    printMessage(&quot;Hello, Unit!&quot;)  // Prints: Hello, Unit!<br>}</pre><pre>//When decompiled, Unit becomes void in Java<br>public static final void printMessage(@NotNull String message) {<br>   Intrinsics.checkNotNullParameter(message, &quot;message&quot;);<br>   System.out.println(message);<br>}</pre><p>Example: Functional Type</p><pre>fun runBlock(block: ()-&gt;Unit) {<br>    block()<br>}<br><br>fun main() {<br>    runBlock { println(&quot;Here&quot;) } // Prints: Here<br>}</pre><p>Here, () -&gt; Unit is a function type and the Unit indicates that this function type does not return any meaningful value.</p><p>In function type mentioning the Unit is compulsory.</p><h3>Nothing</h3><pre>//SOURCE CODE<br>package kotlin<br>/**<br> * Nothing has no instances. You can use Nothing to represent &quot;a value that never exists&quot;: for example,<br> * if a function has the return type of Nothing, it means that it never returns (always throws an exception).<br> */<br>public class Nothing private constructor()</pre><ul><li>Represents the absence of any value indicating that a function will never return normally.</li><li>Subtype of all well-formed Kotlin types, including user-defined ones.</li><li>Used for functions that never return, either because they throw an exception or enter an infinite loop.</li><li>We cannot create an instance of Nothing, nor can any class inherit from it.</li><li>Functions with a return type of Nothing doesn’t return any value not even the default return type Unit .</li><li>The Nothing return type in Kotlin saves us from potential bugs by making it clear that they do not return. When any function having Nothing as the return type is invoked, then the compiler will not execute beyond this function call and gives us the Unreachable code warning.</li></ul><p>Example</p><pre>fun fail(message: String): Nothing {<br>    throw IllegalArgumentException(message)<br>}<br><br>fun main() {<br>    // This will throw an exception and never return normally<br>    fail(&quot;This is an error!&quot;)<br>    println(&quot;Hello&quot;) // Compiler gives warning &quot;Unreachable code&quot;<br>}</pre><pre>//When decompiled, Nothing becomes Void in Java<br>//Void is part of the java.lang package, acts as a reference to objects that wrap the Java primitive type void. It is uninstantiable.<br>@NotNull<br>public static final Void fail(@NotNull String message) {<br>   Intrinsics.checkNotNullParameter(message, &quot;message&quot;);<br>   throw (Throwable)(new IllegalArgumentException(message));<br>}</pre><p>Source Code: <a href="https://github.com/khushpanchal/HappyCoding/blob/master/app/src/main/java/com/khush/happycoding/kotlin/KotlinAnyUnitNothing.kt">Github</a></p><h3>Contact Me:</h3><p><a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a>, <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy Coding ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcaad73fbc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ketch — Android File Downloader Library]]></title>
            <link>https://medium.com/@khush.panchal123/ketch-android-file-downloader-library-7369f7b93bd1?source=rss-7c3779710486------2</link>
            <guid isPermaLink="false">https://medium.com/p/7369f7b93bd1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[workmanager]]></category>
            <dc:creator><![CDATA[Khush Panchal]]></dc:creator>
            <pubDate>Sun, 05 May 2024 14:58:16 GMT</pubDate>
            <atom:updated>2024-09-21T16:59:43.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ketch — Android File Downloader Library</h3><h4>An Android File downloader library based on WorkManager with pause and resume support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCpLdjGrMXPdHklzL_OJqQ.png" /><figcaption>Ketch: Android File Downloader Library</figcaption></figure><h3>About Ketch</h3><p>Ketch is a simple, powerful, customisable file downloader library for Android built entirely in Kotlin. It simplifies the process of downloading files in Android applications by leveraging the power of WorkManager. Ketch guarantees the download irrespective of application state.</p><h3>Why use Ketch?</h3><ul><li>Ketch can download any type of file. (jpg, png, gif, mp4, mp3, pdf, apk and many more) and guarantees download unless canceled explicitly or download is failed.</li><li>Ketch provides all download info including speed, file size, progress.</li><li>Ketch can download multiple files in parallel with support of pause-resume, retry-cancel and deletion of downloads.</li><li>Ketch provides notification for each download providing download info (speed, time left, total size, progress) and option to pause, resume, retry and cancel from notification itself.</li><li>Ketch provides the option to observe download items (or single download item) as Flow.</li><li>Ketch provides various customisation including custom timeout, custom okhttp client and custom notification.</li></ul><h3>Usage</h3><p>Ketch is very simple to use: Add the dependency, pass the url, path and fileName to download and observe the download.</p><pre>// build.gradle<br>dependencies {<br>  implementation &#39;com.github.khushpanchal:Ketch:2.0.0&#39;<br>}<br><br>//Application<br>private lateinit var ketch: Ketch<br>override fun onCreate() {<br>  super.onCreate(savedInstanceState)<br>  ketch = Ketch.builder().build(this)<br>}<br>  <br>//To download the file<br>val id = ketch.download(url, fileName, path)<br>lifecycleScope.launch { // e.g., from activity<br>  repeatOnLifecycle(Lifecycle.State.STARTED) {<br>    ketch.observeDownloadById(id)<br>      .flowOn(Dispatchers.IO)<br>      .collect { downloadModel -&gt; <br>        // use downloadModel<br>      }<br>  }<br>}<br><br>// To cancel the download<br>ketch.cancel(downloadModel.id) // other options: cancel(tag), cancelAll()<br><br>// To pause the download<br>ketch.pause(downloadModel.id) // other options: pause(tag), pauseAll()<br><br>// To resume the download<br>ketch.resume(downloadModel.id) // other options: resume(tag), resumeAll()<br><br>// To retry the download<br>ketch.retry(downloadModel.id) // other options: retry(tag), retryAll()<br><br>// To delete the download<br>ketch.clearDb(downloadModel.id) // other options: clearDb(tag), clearAllDb(), clearDb(timeInMillis)<br>ketch.clearDb(downloadModel.id, false) // Pass &quot;false&quot; to skip the actual file deletion (only clear entry from DB)<br><br>// To observe all the downloads<br>viewLifecycleOwner.lifecycleScope.launch { // e.g., from fragment<br>  repeatOnLifecycle(Lifecycle.State.STARTED) {<br>    ketch.observeDownloads() // other options: observe download by id, by tag<br>      .flowOn(Dispatchers.IO)      <br>      .collect { <br>         //set items to adapter<br>      }<br>  }<br>}</pre><p>To enable the notification, add appropriate notification permission and pass notification config while initialising the library.</p><pre>ketch = Ketch.builder().setNotificationConfig(<br>         config = NotificationConfig(<br>           enabled = true,<br>           smallIcon = R.drawable.ic_launcher_foreground // It is required to pass the smallIcon for notification.<br>         )<br>       ).build(this)</pre><h3>How Ketch works?</h3><h4>High Level Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48v9eg8b1CspPvcd4oSTJg.png" /></figure><h4>Component Details</h4><ul><li><strong>Ketch</strong>: It is the core class client interacts with. It has various exposed functions including init, download, pause, resume, retry, cancel, clearDb, observeDownloads. It has the instance of DownloadManager.</li><li><strong>DownloadManager</strong>: It is the central class of the library that has an instance of downloads database and WorkManager. It is responsible for enqueuing the work request. It directly observes the database carrying all download related information making the database the single source of truth. Additionally this class has observe functions that return the flow of list of DownloadModel (data class carrying all download information) to the client.</li><li><strong>DownloadWorker</strong>: It extends CoroutineWorker for downloading the items in background. It has the instance of DownloadTask, DownloadNotificationManager and Download database.</li><li><strong>DownloadTask</strong>: It has the suspend function download and provides callbacks like onStart and onProgress. It has the length of file and also carries the logic of calculating download speed. It has a DownloadService class that uses Retrofit for making network requests.</li><li><strong>DownloadNotificationManager</strong>: It is responsible for showing the notification to the user. It creates a notification channel and notification. It also sendBroadcast which is received by NotificationReceiver after work is finished.</li><li><strong>DownloadDao: </strong>It carries all database queries for storing, updating or getting download info from database. Library uses ROOM for database.</li><li><strong>NotificationReceiver</strong>: It is responsible for showing the terminating notification to user after DownloadWorker is finished or canceled. It shows Cancel, Failed (with retry and cancel action), Paused (with resume and cancel action) and Successful Notification message.</li></ul><h4>Ketch provides lot more features with plenty of customisation options, check out the GitHub project for more information:</h4><p>Github Project: <a href="https://github.com/khushpanchal/Ketch">https://github.com/khushpanchal/Ketch</a></p><p>If this project helps you, show love ❤️ by putting a ⭐ on <a href="https://github.com/khushpanchal/Ketch">this</a> project ✌️</p><p><strong>Contact Me</strong>: <a href="https://www.linkedin.com/in/khush-panchal-241098170/">LinkedIn</a>, <a href="https://twitter.com/KhushPanchal15">Twitter</a></p><p>Happy coding ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7369f7b93bd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>