<?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 Randy Arba on Medium]]></title>
        <description><![CDATA[Stories by Randy Arba on Medium]]></description>
        <link>https://medium.com/@randy-arba?source=rss-24ec64eb74c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wDsEX8C0_51eIiq6cHht2A.jpeg</url>
            <title>Stories by Randy Arba on Medium</title>
            <link>https://medium.com/@randy-arba?source=rss-24ec64eb74c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:52:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@randy-arba/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[Understanding Context Caching in AI Applications]]></title>
            <link>https://randy-arba.medium.com/understanding-context-caching-in-ai-applications-6fb42e2cafd5?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb42e2cafd5</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 15:03:21 GMT</pubDate>
            <atom:updated>2025-06-28T15:03:21.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VMZJqYnNsWwKen5s" /><figcaption><a href="https://unsplash.com/@kaboompics">Karolina Grabowska</a></figcaption></figure><p>This week, I explored how to optimize AI applications by reducing context repetition during prompting. When you include large context in every request, it consumes significant input tokens, increasing costs with each API call. The challenge is maintaining context without repeatedly sending the same information, which can quickly become expensive as your application scales.</p><p>Context caching is a feature available in AI models like Gemini that allows you to upload content once and store it server-side for a specific time period, known as Time to Live (TTL). This cached content can be referenced in subsequent requests, creating a temporary knowledge base that persists across multiple interactions. Think of it as uploading a document once and then asking multiple questions about it without re-uploading the document each time.</p><p>Context caching works particularly well for document Q&amp;A systems where you’re analyzing lengthy documents with multiple queries, complex RAG systems with large knowledge bases, video and audio analysis requiring multiple processing requests, and consistent system instructions that need to be maintained across sessions. In my case, I focused on consistent system instructions to maintain context across user interactions without repeatedly sending the same prompt context.</p><p>Let me illustrate the cost benefits with a practical scenario. Imagine you have a job search chatbot that answers questions about companies. Your setup includes a company database of 10,000 tokens containing comprehensive company information, with each user asking 5 questions per day. Each question is about 20 tokens, each AI response is 100 tokens, and the AI processing cost is $0.001 per 1,000 tokens.</p><p>Without caching, every question requires re-processing the entire company database. This means each question uses 10,000 + 20 + 100 = 10,120 tokens, so 5 questions consume 50,600 tokens per day, costing $0.051 per user per day. However, with caching, you load the company database once and reference it for all questions. The cache cost is 10,000 tokens × $0.002 per day = $0.02, plus question processing of (20 + 100) × 5 = 600 tokens = $0.0006, for a total cost of $0.021 per day.</p><p>The savings become dramatic when scaling to 100 users. Without caching, you’d pay $0.051 × 100 = $5.10 per day. With caching, you’d pay only $0.02 + ($0.0006 × 100) = $0.08 per day. That’s a 98% cost reduction, and the savings scale dramatically with more users.</p><p>Implementation requires attention to several technical prerequisites. You must always include the version suffix (like -001) when specifying the model, ensure your context is at least 32,768 tokens to meet the minimum requirement, and implement proper cache lifecycle management. It’s important to note that context caching is not available on free tiers — you need a paid plan to use caching features. Attempting to use caching on free tiers will result in a “400: Bad Request” error.</p><p>However, context caching isn’t suitable for every scenario. You should avoid it for small context under 32,768 tokens, single query use cases that don’t benefit from persistence, rapidly changing data that makes caching ineffective, and very low query volumes where there’s insufficient usage to justify caching costs.</p><p>The key benefits include significant cost reduction of up to 98% in high-usage scenarios, maintained context without token repetition, improved performance through faster response times by avoiding repeated context processing, and scalability where cost benefits increase with user volume. Context caching is a powerful optimization technique for AI applications with consistent, large contexts and multiple user interactions. While it requires a paid tier and has minimum token requirements, the cost savings and performance improvements make it invaluable for production applications. The key is identifying use cases where the same large context is referenced multiple times, transforming an expensive, repetitive process into an efficient, scalable solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb42e2cafd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Pre-Mortems Matter in Engineering Teams]]></title>
            <link>https://randy-arba.medium.com/why-pre-mortems-matter-in-engineering-teams-b0447037a0d4?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0447037a0d4</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[postmortem]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[team]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Sun, 18 May 2025 12:27:27 GMT</pubDate>
            <atom:updated>2025-05-18T12:27:27.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S3uG4aM1nEW2qfUd" /><figcaption>Photo by <a href="https://unsplash.com/@dtopkin1?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Dayne Topkin</a> on <a href="https://unsplash.com/photos/macbook-pro-on-white-table-y5_mFlLMwJk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>This week, I learned something that changed the way I think about handling problems in engineering: <strong>the power of a Pre-Mortems</strong>.</p><p>In most teams, when an issue occurs, we react. We investigate the cause, prepare a postmortem document, and try to ensure it doesn’t happen again. This process is valuable — it helps us reflect and improve.</p><p>But what if we could prevent those issues before they even happen?</p><h4>What Is a <strong>Pre-Mortems</strong>?</h4><p>A <strong>Pre-Mortems</strong> is exactly what it sounds like: the opposite of a postmortem.</p><p>Instead of waiting for failure and analyzing it afterward, a Pre-Mortems asks the team to imagine that the project has already failed. Then, everyone works backward to figure out what could have caused that failure. It’s a mindset shift — from reactive to proactive.</p><p>The concept originates from the medical world, where doctors and health professionals try to understand potential causes of death in order to <strong>prevent</strong> them. In the same way, a Pre-Mortems helps teams discover weak points before they become real problems.</p><h4>How a <strong>Pre-Mortems</strong> Session Works</h4><p>Here’s how a typical Pre-Mortems meeting might go:</p><ul><li>The project team gathers and gets briefed on the plan.</li><li>The facilitator (often the team lead or project manager) announces:<br>“Imagine this project has completely failed. It went horribly wrong.”</li><li>Each team member silently writes down all the possible reasons they believe the project could have failed — technical issues, communication breakdowns, unrealistic timelines, unclear requirements, and so on.</li><li>One by one, team members share their reasons. No judgment, just honest input.</li><li>All reasons are collected and discussed. The project manager then looks for patterns and adjusts the project plan to reduce the identified risks.</li></ul><h4>Why It Works</h4><p>A Pre-Mortems does more than just uncover risks early. It also:</p><ul><li><strong>Promotes psychological safety, </strong>people are encouraged to speak up without fear of blame.</li><li><strong>Breaks overconfidence, </strong>it challenges the assumption that “everything will be fine.”</li><li><strong>Adds value to diverse perspectives, </strong>team members bring different experiences and insights, which makes the plan stronger.</li></ul><p>It’s not about being negative. It’s about being realistic.</p><h4>Final Thoughts</h4><p>Pre-Mortems thinking reminds us that failure isn’t always a surprise — sometimes it’s predictable. And if it’s predictable, it’s preventable.</p><p>This mindset can save time, reduce stress, and lead to better project outcomes.</p><p>Let’s not wait until a project goes wrong to learn from it. Let’s learn before it starts.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0447037a0d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write to Think: Preserving the Human Mind in the AI Era]]></title>
            <link>https://randy-arba.medium.com/write-to-think-preserving-the-human-mind-in-the-ai-era-6b5557c689a4?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b5557c689a4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[write]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[books]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Sun, 11 May 2025 12:02:41 GMT</pubDate>
            <atom:updated>2025-05-11T12:02:41.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h8rGKjXFidgDGsFd" /></figure><p>You’ve probably noticed it too: everywhere you look, every headline you read, every trend you scroll past , it’s all about AI.</p><p>For me, AI is no longer just a trend. It’s in my work, my daily tasks, and even how I think. It’s become part of my life. Everything that <em>can</em> be AI-powered is heading in that direction. And yes, many people are afraid, afraid that AI will replace human jobs and leave us behind.</p><p>They’re not entirely wrong. AI <em>can</em> do many things, and it’s only getting better. But it still lacks something deeply human. As Jensen Huang once said, AI won’t replace people, but people who use AI will replace those who don’t.</p><p>Still, AI isn’t wise. It doesn’t make mistakes the way we do, and that’s part of what makes us as a human.</p><p>To me, AI feels like a second brain. It helps me with everyday tasks: replying to emails, enhancing my writing, designing, programming, photo editing, and more. But here’s my rule: <strong>before AI becomes your second brain, you must master your own first</strong>. Use AI as a tool, but don’t let it think for you. If you stop growing, AI might not just help you, it might replace you. I don’t mean to scare you, but you need to do something.</p><p>If AI becomes your second brain, <strong>don’t let it replace your first</strong>.</p><p>So, what truly makes us human? Is it our mistakes? No, we’re more than that. What AI still lacks (at least for now) is <em>true creativity, critical thinking, and discernment</em>. These are skills worth protecting.</p><p>One way I believe we keep those skills sharp is simple: <strong>write</strong>.</p><p>Writing is hard. I’ve been through it. I was once a campus journalist, then a book and magazine designer. You’d think it’d be easy for me, but no. After switching to a career in programming (which involves a lot of typing), I realized typing code is not the same as writing. Typing is input. <strong>Writing is thought.</strong> Writing is about turning your own ideas into something real, into words.</p><p>And like anything you don’t practice, writing gets harder if you stop doing it.</p><p>So just start. Don’t overthink it. Take a small step. Start a daily journal. Write a short reflection. Note something important from your day. Clean it up later. Make it a habit.</p><p>Also, don’t forget: <strong>writing starts with reading</strong>. The more you read, the more words you’ll have when it’s time to write. And the best way to build critical thinking is the same way you build good writing, not just by writing, but by <strong>reading first</strong>.</p><p>So, pick up a book. Read. Let it feed your thoughts.</p><blockquote><strong>Writing is fueled by reading. Write it down just for your mind’s sake.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b5557c689a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensure process only once Flutter? use AsyncMemoizer]]></title>
            <link>https://randy-arba.medium.com/ensure-process-only-once-flutter-use-asyncmemoizer-70b7b0a1cbcd?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b7b0a1cbcd</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[process]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Sun, 04 May 2025 13:38:07 GMT</pubDate>
            <atom:updated>2025-05-04T13:38:07.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j5UqDnowmcxmrKOZ" /><figcaption>Photo by <a href="https://unsplash.com/@razipourjafari?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">razi pouri</a> on <a href="https://unsplash.com/photos/a-couple-of-birds-sitting-on-top-of-a-power-line-yiOuQ0_T30I?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>I understand, when you have a use case where a process should only run the first time and not again, or when you want to avoid triggering multiple requests at the same time, AsyncMemoizer can help solve the problem.</p><p>And what the meaning of <strong>AsyncMemoizer</strong>?</p><h3><strong>AsyncMemoizer</strong></h3><p>Just like the name, AsyncMemoizer combines asynchronous operations with memoization — an optimization technique used to speed up programs by storing the results of expensive function calls. AsyncMemoizer ensures that an asynchronous operation is executed only once, preventing redundant calls during repeated function invocations or while the operation is still in progress, which improves performance and efficiency.</p><p>To save the result of an async operation (memoize), create an AsyncMemoizer instance with the correct output data type. Then, place the async operation you want to memoize inside the runOnce function provided by AsyncMemoizer.</p><p>AsyncMemoizer in Flutter (from the async package) is useful when you want to <strong>cache the result of an asynchronous computation</strong> so that it <strong>only runs once</strong>, even if called multiple times, a pattern often used in initState, build, or didChangeDependencies.</p><p>Benefits of <strong>AsyncMemoizer</strong></p><ul><li><strong>Prevent duplicate async calls</strong>, ensures a function is executed only once, even if called again before the first completes.</li><li><strong>Useful in build() or widget lifecycle methods</strong>, prevents re-triggering async tasks on every rebuild.</li><li><strong>Saves resources</strong>, avoids repeated expensive operations like network calls or database queries.</li></ul><p>Let’s say you want to fetch user data from an API, but only <strong>once</strong>, even though build() could run multiple times</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPSrlT6PGtb7slFJ7JdgOw.png" /></figure><p><a href="https://pub.dev/documentation/async/latest/async/AsyncMemoizer-class.html">AsyncMemoizer class</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b7b0a1cbcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI implementation in Kotlin Multiplatform using the Reaktive library (Part 2)]]></title>
            <link>https://randy-arba.medium.com/mvi-implementation-in-kotlin-multiplatform-using-the-reaktive-library-part-2-50cafdfcb35a?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/50cafdfcb35a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 06:27:33 GMT</pubDate>
            <atom:updated>2022-09-30T06:27:33.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BJshrIjyPGinbS5d.png" /></figure><p><strong>This Part</strong> one contain the basic of MVI pros and cons and also why i choose MVI for KMM.</p><p><strong>Part Two</strong> will explore more about MVI implementation on KMM, also few library that support on it such as Ktor, Kotlin-Serialization, Jetpack Compose and Swift UI.</p><p><strong>Preparation</strong></p><p>Component that you need to prepare and take a note based on Experience:</p><ul><li><a href="https://kotlinlang.org/docs/multiplatform-mobile-setup.html#check-your-environment">Download</a> KDoctor <strong>KDoctor works on macOS only</strong>. make sure when run Kdoctor all required component should available.</li><li>Install <a href="https://mac.install.guide/commandlinetools/index.html">Commandline</a> for Xcode (Xcode-cli), ensure command line version match with Xcode.</li><li>Note for Kdoctor, if result came with suggestion to relate Ruby version , so please download Ruby version that Kdoctor suggest using <a href="https://rvm.io/rvm/install">RVM</a>. But if you have multiple ruby version you can choose one <strong>rvm use ruby-{version} </strong>on terminal.</li><li>After cli xcode installed so it must restart first before. sudo xcode-select -r</li><li>Check CocoaPods install and clang-llvm-apple component if needed.</li><li>if build ios still failing please remove framework file first or check cocoapod with pod setup, pod install, pod init, and cocoapods-generate install.</li><li>Then Run ./gradlew :shared:embedAndSignAppleFrameworkForXcode</li><li>Dont forget to install jdk full 18 to prevent failed when run/build in Xcode because it will run gradle script.</li><li>delete ios_app in framework directory, if failed find id Pods_iosApp.</li></ul><p>Make sure you already have KMM plugin in Android Studio, if not please download from marketplace. Create new KMM Module (Kotlin Multi Platform Library) please specify iOS framework distribution as Regular Framework, wait until Android Studio success download all component, after success u should see project directory like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*xDDyBMr-t4eSdR1zCoD5rQ.png" /></figure><p>AndroidApp contain Android module only all project relate Android will process on that directory, then iosApp module is project for Ios code like swift, etc the project only can be loaded using xcode.</p><p>Run for first time using android and Ios. make sure gradlew build is success then icon of run on Android studio not show Error (x).</p><p><strong>MVI Pattern Preparation</strong></p><p>Create another new library module (mvi) on Android studio, this module contain MVI pattern abstraction. then we need create parent module that have MVI module and Shared module. Parent module will rename as shared and for previously shared module will change into main. So it will become like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*Icgw6NfJHWxevWnq50fxSw.png" /></figure><p>Shared directory will contain all shared module include MVI module and main share module. why we need separate becuase MVI module only contain MVI pattern abstraction that can be adjust and scoped on abstraction level.</p><h3><strong>Shared (Main Module) Intro</strong></h3><ul><li>Please check gradle file from this link.</li></ul><p>Main Module will accomodate shared business logic part that include commonMain, androidMain, and iOSMain, etc. It this module will depend on the kotlin gradle configuration and sourceSets, such as android(), jvm(), and ios binaries. So dont forget to make sure the name of your sourceSet is avalaible in this module.</p><p>commonMain directory will provide business logic specific whereas androidMain and iosMain is for platform specific and each of this module/domain can configure separate dependencies in gradle. Why we need separate androidMain and iosMain separation? because commonMain will free from platform dependencies so if you want to check each platform specific you can communicate androidApp and iOSApp module via <strong>actual</strong> and <strong>expect</strong> keywrod that reserved by kotlin KMM API. Below example need.</p><p>Okay lets have an example, there is usecase where in commonMain will handle function based on prod and debug behavior, so how commonMain validate each platform is debug version? we cant obtain platform specific on commonMain because it must be free all platform related.</p><p>so we must create this in commonMain module,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CePsDm5wDAD06eKOJ-0Wqw.png" /><figcaption>in commonMain module directory</figcaption></figure><p>After that we can create this code on iosMain and AndroidMain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uHYWcCZybbPtZueZcD5Cg.png" /><figcaption>in iosMain module directory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyIIe9eeyGnel5sjWokh3Q.png" /><figcaption>in androidMain module directory</figcaption></figure><p><strong>Please take a note</strong> the stucture directory of file must same, example if those code (contain expect keyword) file in commonMain in root of directory so do in androidMain and iosMain, if structure of directory is different it will show error “<strong>Actual class ‘Config’ has no corresponding expected declaration</strong>” on iosMain and androidMain module that contain actual keyword. Below is sample structure.</p><ul><li>commonMain -&gt; platformDir -&gt; file that contain expect keyword</li><li>iosMain -&gt; platformDir -&gt; file that contain actual keyword for iOS</li><li>androidMain -&gt; platformDir -&gt; file that contain actual keyword for android</li></ul><h3><strong>Shared (MVI module)</strong></h3><ul><li>Please check gradle file from this link.</li></ul><p><strong>TypeAliases Kotlin</strong></p><p>Getting Started of MVI based on first blog that MVI have two basic (Store/model and View), but create the less depend class first using typealias to simplify return type of abstraction. For Intent processing, we use <strong>Actor</strong> a function that take current state and an <strong>Intent</strong> and return stream <strong>Effect</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0cAVxEBjnnP3rE-Z420mA.png" /><figcaption>Typealias Actor that have State, Intent, and Effect processing type</figcaption></figure><p>After that we can introduce <strong>Reducer, </strong>a function that accept current <strong>State</strong> and an <strong>Effect</strong> result from actor and then return new state. We can include all the typealias in one file (Typealiases.kt)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OukVM0vj8exlSGysvq2KJQ.png" /><figcaption>TypeAlias Reduce that have State and Effect processing type</figcaption></figure><ol><li><strong>Store/Model</strong></li></ol><p>Store is represent model in MVI, it accept Intent and return stream of State type, the current state will be emitted when subscribing to stream state. has two generic param input and output state, then extend Consumer of Intent, Observable State, Disposable type. After abstraction store already created and continue to create helper based from Store abstraction we call it StoreHelper. Why we need this because it’s not very convenient to implement such an interface every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciXQs8bjn7IW3q9tqRbu8Q.png" /><figcaption>Store interface for abstraction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iDfkusR_Me2-61aAfG96Q.png" /><figcaption>StoreHelper</figcaption></figure><p>So StoreHelper will take three parameter, <strong>initialState</strong>, <strong>actor</strong>, and <strong>reducer</strong>. action and reducer use typealiase that we already define earlier. StoreHelper also have three generice parameter input <strong>Intent</strong> and <strong>Effect</strong>, then output <strong>State. </strong>Those class will extends State as Stream and have DisposableScope type (interface from Reaktive for managing subscriptions). Please take a look for first blog Store diagram.</p><p>There two function that created on StoreHelper, <strong>onIntent</strong> and <strong>onEffect.</strong></p><p><strong>OnIntent Method</strong></p><ul><li>Pass Intent argument</li><li>Invoke Actor then put current State and Intent, it will subscribes to the stream of Effects.</li><li>Pass stream onNext (Effects type) to the <strong>onEffect</strong> method</li><li>Stream of the subscription on the ThreadLocal (<a href="https://github.com/badoo/Reaktive#thread-local-tricks-to-avoid-freezing"><strong><em>isThreadLocal</em></strong></a><strong><em>) </em></strong>for<strong><em> </em></strong>avoids freezing in Kotlin/Native</li></ul><p><strong>OnEffect Method</strong></p><ul><li>Pass Effect argument</li><li>Put new State to the <strong>BehaviorSubject</strong> that we already define, which leads to emission of the new state for all subscribers</li><li>Invoke Reducer and passes the current State and the Effect to it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L41nfyQmp8XqUiJj.png" /></figure><p><strong>2. View</strong></p><p>This is the main part of MVI which accept store and pass it into View via render, i can say MVI pattern different with other pattern is in this view. MVI only receive in one stream called render and then create view based on state. So i can say that view will created and compose via render (it match and fully support with Jetpack Compose and swiftUI).</p><p>First we need create abstraction MviView interface. it consist two generic parameter input model and output Event, accept model via render method and then return stream of event via event variable.</p><p>For client android/ios not direct interact with event and render property so we will create abstract class extending MviView interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0sDq2KjGXM8ebemxv26ZA.png" /><figcaption>MviView Interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCQWVMBlufcnaL-zTfCg3Q.png" /><figcaption>AbstractMviView class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xrkPK5UtT7XV1gn0.png" /></figure><p><strong>Store</strong> produces <strong>States</strong> that are converted to <strong>Models</strong> and displayed by the View. then produces <strong>Events</strong> that converted to <strong>Intents</strong> and delivered to the <strong>Store</strong> for processing. This will eliminates coupling between <strong>Store</strong> and <strong>View</strong>. The View can work directly with <strong>States</strong> and <strong>Intents</strong>.</p><h3>Shared (Main Module)</h3><p>For example case, we use Pokemon Prefix name but the API using Anime Api hahaha still on development process in the future will be change.</p><p><strong>Store<br></strong>Create store interface that extend Store from Mvi module. this store will load all data related. This interface consist sealed class as Intent and State Data class. this interface define as internal, mean t will be visible everywhere in the same module.</p><p>So all action or intention to do will on this sealed class, because we only have one action/intention todo such as <strong>reload()</strong>. in other part like State data class we have flag <strong>isLoading</strong> and <strong>data</strong>. <strong>Data</strong> it self contain <strong>success data</strong> and <strong>error.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDcFl17ka1xF-0dvh217RA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4B7AEOoDCIRYvMXmM62ySw.png" /></figure><p>Okay after that we implement Store into StoreImp that take one parameter usecase and have disposableScope. below StoreImp class there is sealed class Effect is related of Loading states.</p><p><strong>View</strong></p><p>Create View that extend MviView from Mvi module the generic parameter will create on this interface, There two part <strong>Model</strong> data class and <strong>Event</strong> sealed class. This View class that consist <strong>model</strong> and <strong>event</strong> is part that communicate with the platform view. Event will fire from view platform and then model is data that pass on render to compose view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsBBU4ro47wNyJya-KsaoQ.png" /></figure><p><strong>Mapper</strong></p><p>Mapper help to transform type into another type of object, in this part we transform State into Model and Event into Intent, maybe you ask why Event need to transform why not directly become Intent, because we try to decouple <strong>Action</strong> from <strong>View</strong> and from <strong>Store</strong>, so if we there is case if <strong>action</strong>/<strong>event</strong> from view can reuse same <strong>action/Intent </strong>on Store. Example;</p><p>We have two event in view that trigger <strong>Refresh</strong> and <strong>Search</strong>, but in Intent Store we can reuse <strong>Reload() </strong>that have same result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB4y6kKL9Hf2mdDayX5HEQ.png" /></figure><h3><strong>Data Source</strong></h3><p>Data source is where Data come from and provide data into other part. Data source will consist <strong>Model</strong>, <strong>Repository</strong>, <strong>UseCase. Model</strong> that we mention here is not model in MVI pattern but model data from response API it contain Data class and serialization annotation example, SearchApiResponse and ResultResponse.</p><p><strong>Repository</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuPMZtvgSaHIogbmZpaZYg.png" /><figcaption>IndexRepository interface for abstraction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FveYxS-1UCpT_RmWUMbrNA.png" /><figcaption>Implementation from IndexRepository</figcaption></figure><p><strong>UseCase</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWd2zKDVqvygZlPmWntKsQ.png" /><figcaption>UseCase Interface Abstraction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uOriV0-aVKHxZJ5cQhNMg.png" /><figcaption>Create Index that implement from UseCase</figcaption></figure><p><strong>Client API</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--lxo4eXDIYan6L7zauUOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VC7VrYt6J2AVaIy23uR8Fw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50cafdfcb35a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI implementation in Kotlin Multiplatform using the Reaktive library (Part 1)]]></title>
            <link>https://randy-arba.medium.com/mvi-implementation-in-kotlin-multiplatform-using-the-reaktive-library-part-1-2c283c9e50de?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c283c9e50de</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 16:01:10 GMT</pubDate>
            <atom:updated>2022-09-09T16:01:10.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJFNFujon42Fw7LyzqUsTg.png" /></figure><p><strong>This Part</strong> one contain the basic of MVI pros and cons and also why i choose MVI for KMM.</p><p><strong>Part Two</strong> will explore more about MVI implementation on KMM, also few library that support on it such as Ktor, Kotlin-Serialization, Jetpack Compose and Swift UI.</p><h3>MVI actually inspire with Redux from react, what is redux?</h3><p><strong>Redux</strong> is a pattern and library <strong>for managing and updating application state, using events called “actions”.</strong> It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion. This is a very similar pattern to MVVM, with some important differences. In many ways it’s a merging of MVVM &amp; Redux.</p><p><strong>The purpose of MVI</strong> is managing and updating application state using event that called actions, with rules ensure that the state can be only be updated in predictable. Undirectional and cyclic data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3yq5LG9RNFpsWb0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1m2zKyegcRuVAtmE.png" /></figure><p><strong>MVI</strong> or you can call Model View Intent, as you can see from above that onlly contain and circulate two component <strong>view</strong> and <strong>model</strong>, the data flow only come from one direction. The State come from Model and then Intent come from View and enter model for processing. Those circulation is Called Undirectional DataFlow</p><p><strong>Model</strong>, A Model represent as a ViewState, contain all necesssary to render the view. In some part Model represented by entity called <strong>store</strong>. a name that borrowed from redux, but its not exactly name, some developer on MVICore name Model as Feature.</p><p><strong>View</strong>, observe user an system event, as a result it set intentional triggered action and it listen and react in state of model.</p><p><strong>Intent</strong>, Intentional to do somethings, Represent future action that changes the state of model.</p><p><strong>Actor</strong>, a function that takes a current State and an Intent and returns a stream of Effects (results).</p><p><strong>Reduce, </strong>a function that accepts a current State and an Effect (result) from Actor and returns a new State.</p><p><strong>Store</strong>, Represent model from MVI, should accept intent and provide stream state.</p><p><strong>View</strong>. It should accept (render) Models and provide a stream of Events. Here is the interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NNYnjVRuN5mStsix.png" /></figure><p><strong>Why no MVP?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UGL2VssJw26sa7LS.png" /></figure><p>The defining feature of MVP is that data is communicated back to the view imperatively. Strangely enough this is likely impossible to implement in Compose. Let’s take a look why.</p><p>To imperatively update the UI, presenters rely on having a reference to the view, which is usually an activity or fragment injected into the presenter as an interface. The presenter can call functions on the interface to cause changes to the UI. But a quick glance at a composable shows there’s no return value — so no view references to pass to our presenter, because compose doesnt return anything.</p><p>There is also potentially the option of using <a href="https://foso.github.io/Jetpack-Compose-Playground/general/compositionlocal/">CompositionLocals</a> in some way to make MVP work, although it seems a bit of an abuse, and if you’re imperatively setting data to trigger re-compositions you may as well cut out the middle man and use MVVM.</p><p>So it’s probably safe to say that if you’re excited about integrating Compose into your MVP-based-app the place to start is probably in migrating away from MVP. Which is also suggested within the <a href="https://developer.android.com/jetpack/compose/interop#arch-source-of-truth">Compose docs</a>:</p><blockquote><em>Unidirectional Data Flow (UDF) architecture patterns work seamlessly with Compose. If the app uses other types of architecture patterns instead, like Model View Presenter (MVP), we recommend you migrate that part of the UI to UDF before or whilst adopting Compose.</em></blockquote><p>Where MVVM differs from MVP is in how data is communicated back to the view. Rather than imperatively calling the view, in MVVM changes are described by data which are then observable by the view. The UI can then reactively re-compose itself based on the new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4DOvz9aGNbsvPgQz.png" /></figure><p><strong>Const MVI trade off.</strong></p><ul><li>more boiler plate. More code to write.</li></ul><p><strong>Pros MVI trade off,</strong></p><ul><li>MVI is a reactive model, passing in parameters through a unique entry, and receiving results and completion responses from a unique exit.</li><li>Large amount application state in different many places in app.</li><li>The App state is update frequently. <strong>not agreee</strong></li><li>The logic of update may be complex.</li><li>The app is huge and large size code base that handle and worked by many people</li><li>The <strong>state</strong>, the source of truth that drives our app;</li><li>The <strong>view</strong>, a declarative description of the UI based on the current state</li><li>The <strong>actions</strong>, the events that occur in the app based on user input, and trigger updates in the state</li></ul><p><strong>How Migrate from MVVM/MVP</strong></p><ul><li>Define States based on view and activity changes</li><li>for MVP pattern replace all contract view such as view.onSuccess() into view.render(state)</li><li>for MVVM replace all LiveData&lt;Type&gt; into LiveData&lt;State&gt;</li><li>Define state machine with clear API with input and output.</li><li>Define Intent that trigger input from State Machine.</li><li>Trigger intent from View layer</li></ul><p><strong>Shared Module</strong></p><ul><li>We managed to put all the code (except UI) into the shared multiplatform module. All the logic plus wirings and conversions between the logic and the UI are shared.</li><li>The implementation of the UI will be very simple: you only need to render the incoming Models and produce Events</li><li>Module integration is also simple. All that is needed is to:<br>- implement the KittenView interface (protocol)<br>- instantiate the KittenComponent<br>- call its life cycle methods at the right time.</li><li>This approach avoids the leakage of Rx (or coroutines) into the platforms. This means that we don’t have to manage any subscriptions at the application level</li></ul><p>An action is a plain JavaScript object that has a type field. You can think of an action as an event that describes something that happened in the application.</p><p><strong>KMM</strong></p><p>We believed in the KMP approach: to share logic without mandating an entire architecture. We hoped that sharing logical components between mobile apps would reduce the development time, improve the quality of the code, and have no impact on performance.</p><h3>Kotlin Multiplatform Pros:</h3><ul><li><strong>Faster Development using single sources</strong>. For a new feature, one developer (e.g., an iOS developer) would add model objects, networking, business logic, and unit tests to the multiplatform module. Then the other (e.g. an Android developer) would just plug the feature in. This helped us cut the development time exponentially as we were developing features.</li><li><strong>Improved Code Quality</strong>. inherent modularity and testability of the multiplatform code we wrote.</li><li><strong>Maintainable Code.</strong></li></ul><h3>Kotlin Multiplatform Cons:</h3><ul><li><strong>Longer Project Setup. </strong>Git repository management, Jira tickets, CI/CD, etc. We came up with several approaches before finally finding the one that worked well for us.</li><li><strong>Requires a Cross-Functional Team, </strong>Kotlin/Multiplatform worked well for us because our iOS development team is enthusiastic about learning Kotlin. If this were not the case, the development of almost all of the common code would have fallen on the Android developers and left iOS developers waiting for the business logic to be ready. The cross-functionality of our developers paved the way for multiplatform development.</li><li><strong>New level of iOS Debugging, </strong>In particular, the error logs were usually generic and unclear. Sometimes, this slowed us down measurably.</li><li>Multiplatform projects are currently in alpha. Language features and tooling may change in future Kotlin versions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c283c9e50de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wanna use Jetpack DataStore?]]></title>
            <link>https://randy-arba.medium.com/wanna-use-jetpack-datastore-b50c023daca1?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b50c023daca1</guid>
            <category><![CDATA[data-stores]]></category>
            <category><![CDATA[json-serialization]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 02:50:09 GMT</pubDate>
            <atom:updated>2022-08-03T02:50:09.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*857zJNyF78FWa9Ac" /><figcaption><a href="https://unsplash.com/@petrebels">https://unsplash.com/@petrebels</a></figcaption></figure><p>I have a bad experience using SharePreference because got crashed after revamping the feature. The root cause is the scheme of string JSON is not valid and fails to parse (Runtime Exception), actually my SharedPreferences save object data and format it into string JSON using Google Gson so it can be stored in string type, but when revamp I change model data and entity. My mistake is not to check the old data structure/scheme so it triggers a crash that loads the old scheme and does not match with the new scheme. Even those repositories of responsibility load local data not being added try and catch with a default value.</p><p>Therefore I try to use try and catch for loading local data if there is an error parse trigger, but I think there is still a part that needs to improve about this approach. because our current repository already uses Rxjava/RxKotlin we can make it observable to handle errors, but I think it needs to take effort and must have another abstraction or bridge helper to this. This idea not only supports error handling but also gives some long-running task processing on observable that can be supported by Rxjava/RxKotlin. Another walk-around is using third parties library, such as Jetpack DataStore.</p><p><strong>Cons SharedPreferences</strong></p><ul><li>Unfortunately yeah I already mention before, <strong>Synchronous work</strong>, SharedPreferences runs its read/write operations, except apply() function, on the main thread. because of this disadvantage,</li><li>Blocking the UI thread when making calls or inconsistent, persisted data throughout your app.</li><li>Error Handling SharedPreferences throw parsing errors as runtime exceptions, making the app vulnerable to trigger crashes.</li><li>None type safety and data consistency, Using key-value for saving and retrieving data doesn’t provide type safety protection.</li></ul><p><strong>Jetpack DataStore lib,</strong></p><p>DataStore is a library from google that store key-value pairs or type object that concurent(Rx and coroutine) running and support protocol buffer. You must be already using shared preferences on Android and the behavior is same, but some of pitfalls of Shared Preferences will covered with DataStore.</p><p>There is another alternative for simple store key value such as Paper it also support on RxJava/RxKotlin. but when we compare those library still, the library is lack support or maintenance, Based on my experience using Paper library, it is awesome and can mix with RxJava support not only that Paper also supports not only primitive data support but also support data class object. So I would recommend a library from Google officials like jetpack datastore that long term support.</p><p>With the usage of SharedPreferencesMigration we have the opportunity to migrate SharedPrefrences to DataStore. Related article on this topic: <a href="https://developer.android.com/codelabs/android-preferences-datastore#6">Working with Preferences DataStore - Codelabs</a>.</p><p><strong>Pros Data Store</strong></p><ul><li>Preferences DataStore. (DataStore is safe to call on the UI thread because it uses Dispatchers.IO under the hood) <strong>Non-blocking UI thread DataStore</strong> was built to address all of these issues.</li><li>However, with Proto DataStore, you can predefine a schema for your data model and get the additional benefit of <strong>full type safety</strong>.</li><li>Safe runtime exception.</li><li>Has transaction API that strong consistency guarantees</li><li>Handle data migration</li></ul><p>Cons Data Store</p><ul><li>if you concern about <strong>security</strong> and encryption current data store is not provided yet, but from the <a href="https://issuetracker.google.com/issues/167697691?pli=1">issue tracker, </a>they got high priority because many people still consider encryption for the data store before the migration happens so stay tuned and hope they will add ASAP. Perhaps you can implement the same way as <a href="https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences">EncryptedSharedPreferences</a></li><li>DataStore requires a lot of boilerplate. 100+ lines of code in UserPreferencesRepository for two preferences. Adding Another preference would require changing code, in many different places at least four. This is just another opinion for a person who implements this approach because I believe people will handle and implement it in a different way.</li></ul><p><strong>What if, you still use SharePreferences?</strong></p><p>If you insist on using shared Preferences and not using DataStore because still does not fit with your criteria maybe there are alternative approaches, which better and easier to scale:</p><ul><li>Add Kotlin delegates (You can use your own or use another used <a href="https://github.com/NaluLabs/prefs-delegates">library</a>). The result is type-safe and concise: each property declaration with a default value. Great for most cases, support thread-safe, but it did not provides some transactional guarantees or support complex/custom data types without an extra step.</li><li>This step is already mention above, using RxJava or Stateflow holding a data class, plus a coroutine that observes it in the background and saves to disk as JSON string in vice versa you can load again using serialize provider like Google GSON. If you feel bored using GSON maybe another walk around using specialized <a href="https://github.com/erdo/persista">Persista</a>, Support custom data types &amp; subscribing to updates every transaction.</li></ul><p>Please comment below if you have another opinion or experience about datastore implementation. Hope we can discuss it there. Thanks all. :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b50c023daca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin —  Delegate Properties to Validate Value of Your Class]]></title>
            <link>https://randy-arba.medium.com/kotlin-delegate-properties-to-validate-value-of-your-class-431ab976b787?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/431ab976b787</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Sun, 22 May 2022 14:48:27 GMT</pubDate>
            <atom:updated>2022-05-23T01:48:55.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9FZ-bHIoRXYKDwxF" /><figcaption>Filter for morning coffee, Image from <a href="https://unsplash.com/@nixcreative">Tyler Nix</a></figcaption></figure><h3>Kotlin — Delegate Properties to Validate Value of Your Class</h3><p>Please tell me, if you have a case that which you should filter value to your object class. What should you do? the common case is to validate the condition of value before storing on an object during or after instantiation. Below is an example code before inputting it into UserProfile, check the condition, then trim the character, after that convert to uppercase for name only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LI1G86ZIEXRxMi0LwpWhiQ.png" /></figure><p>Hmm, looks like those approach is common behavior, but the problem is you need to create validation for each you want to put in UserProfile object, and it&#39;s not effective. the other approach you can create an extensions function, but it&#39;s not our purpose for this article, so let&#39;s see if we can use delegation properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4JZgvS0DIVRtyR771nbjw.png" /></figure><p>Yeah, now we can use this every time, no need to create validation before on object. but I think we can improve it a little bit, you can see the code write twice validation although it just only differentiates by value containing “@”. So how we can improve?</p><p>Using a class that extends ReadOnlyProperty or ReadWriteProperty Interface can look better. Because that Interface defines getValue() that used to provide the current value of the delegated property for reading. The purpose same as the name, the interface ReadOnlyProperty cant write, only Read, so setValue is not provided. The ReadWriteProperty(FYI ReadWriteProperty is inherited from ReadOnlyProperty) defines setValue() methods that can be used as update value of the value property.</p><p>Based on those explanations we need to create ValidateDelegate class, after that, we create a new variable to temp store value, then we need to pass the required value parameter to setValue() and getValue().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqCXWw0TmjPU2NtwZYRcPQ.png" /></figure><p>Above is an example of how to use ValidateDelegate and using operator keyword for setValue() and getValue() method. I only use name variable for example to make it short, you can create email validation as well. After you implement the code above you can use that for all classes that need validation of the variable, the reusability of ValidateDelegate.</p><p>Property delegation has a powerful function. Tips and exploration is needed to adapt to the real use case. The purpose of delegation is to write code that can manage the properties and support the shared logic to all classes that needed to use that. So we can increase our reusability code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XysY_L118L_7oy2zp4zWg.png" /><figcaption>Please take note of this parameter during create delegation class.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=431ab976b787" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin tries to Delegate]]></title>
            <link>https://randy-arba.medium.com/kotlin-tries-to-delegate-afd5c300ccca?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd5c300ccca</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[delegate]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Mon, 16 May 2022 17:46:09 GMT</pubDate>
            <atom:updated>2022-05-16T17:46:40.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4HOQPJl5lNfkJ5K4" /><figcaption>Image from : <a href="https://www.pexels.com/@divinetechygirl/">Christina Morillo</a></figcaption></figure><p>What is <strong>Delegation</strong>? based on vocabulary Delegation definition means, the act of empowering to act for another, <em>the delegation of responsibilities</em>. A common case is <strong>when you tell someone to get your mail for you</strong>. The definition of a delegate is a representative authorized to speak or act for others.</p><p><strong><em>Giving one responsibility of doing work to another one.</em></strong></p><p>So what relation with Kotlin language, Kotlin has a property called Delegate properties, the purpose of this properties is same what vocabulary. Kotlin delegate can assign work to another. Below is an example I use TeamLead and TeamMember concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoSV8EqCx3rFIgFwRPyBow.png" /></figure><p>We have an Interface <em>Human</em> class that has <em>leadDailyStandup()</em> functions. After that, we will inherit those class into <em>TeamLead</em> class and override <em>leadDailyStandup()</em> functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-UPuemsGpoAz83706KdsQ.png" /></figure><p>After <em>TeamLead</em> class is already defined, so we will give another team member opportunity to lead daily standup. TeamLeader needs to try to increase ownership of team members and learn leadership using daily standup as lead on the meeting so they delegate it. The leader will give them the template and train how to lead for daily standup meetings.</p><p>We can create another class that inherits the <em>Human</em> class and passes <em>TeamLead</em> type data as an argument which means one of the responsibilities will pass into another class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ymj33wWVXijYsy-Nm9ojA.png" /></figure><p>Create an object-based class that is already created on <em>main</em>() function and execute, below is the example of the <em>main</em> function()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kepPNkeB39cHNpMLrDbmFg.png" /></figure><p>Below is the result of the above, we pass <em>teamLead</em> parameter into <em>TeamMember</em> class we called Helper, and the conclusions of the output are Team lead will do help team members for daily standup and himself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCoXiNsQhxo8tMmU1YLBOQ.png" /></figure><p>The code below actually can be improved and reduce the line code using delegate properties from Kotlin. Removing boilerplate and turn into one line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ymj33wWVXijYsy-Nm9ojA.png" /><figcaption>Before using Kotlin delegate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Xt_okSzxyLcc5iWfmC69g.png" /><figcaption>After using Kotlin delegate.</figcaption></figure><p>The purpose remains the same as the result, it’s just reducing the line of code. Kotlin has several keywords and APIs that need to explore, for example, Delegate properties. The real case using Kotlin delegate is, related the abstraction and inheritance.</p><p>The result is based code above, <em>Team Lead can delegate to Team members after he trains them for daily standup.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd5c300ccca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Approach to Create Mapper using Kotlin Delegated Properties]]></title>
            <link>https://randy-arba.medium.com/different-approach-to-create-mapper-using-kotlin-delegated-properties-6c6463b7a801?source=rss-24ec64eb74c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6463b7a801</guid>
            <category><![CDATA[structured-data]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[language]]></category>
            <dc:creator><![CDATA[Randy Arba]]></dc:creator>
            <pubDate>Sat, 07 May 2022 16:18:58 GMT</pubDate>
            <atom:updated>2022-05-07T16:20:15.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*euf_r28WOCLR3zjW" /><figcaption>images from <a href="https://www.pexels.com/@katerina-holmes/">https://www.pexels.com/@katerina-holmes/</a></figcaption></figure><p>This is just another learning path using Kotlin language, last time I focus on Dart language for flutter development. So for this part, I gonna create another mapper using Kotlin delegated properties, if you already know this method you can ignore this article. :D</p><p>All developers already know about mapper, this mapper is taken responsibility to transform one data class object into another object, it usually happens on getting data from API response, From API response will map into the specific data that we need instead of getting a bunch of response API data.</p><p>How about DTO, the goal remain the same as Mapper, DTOs or Data Transfer Objects is an object that is used to encapsulate data, and send it from one to another. the main benefit of those DTO and Mapper is that it reduces the amount of data that needs to be sent across the wire in distributed applications. So I just using DTO keyword from here. let&#39;s start.</p><p>As the use-case we use Room integration we need to create Entity data that is used as the name of a table field or insert data into local data. usually, we need to create Entity class and a normal data class, for example, we create ProfileEnitity.class and Profile.class. Normally you will create like this for Mapper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDo0kUfabZsI-6L8xbneuA.png" /><figcaption>Using function inside Entity class. Profile Entity map into Dto data class properties</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-25hl1ecoOq9pPNMTkOGQ.png" /><figcaption>Constructor use as a mapper. It maps Entity properties to Dto properties.</figcaption></figure><p>Both have same goals, but the second one less code and convient to use. the first one is we must create function inside data class, so every changes of target tranformation will affect the class, we should reduce changes of data domain model, so we need separation, extensions function is come to rescue, we use as the second approach on above DTO sample. Okay but we have another approach to do this, we using delegated properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuCfJ93bQmSNKZb9MjajwA.png" /><figcaption>Another approach using delegation to DTO class</figcaption></figure><p>Hmmm still look same right? just fancy on the variable properties on ProfileDto class. but wait you should check this out why its have differences compare previous.</p><p>Delegated property is not truely properties of those class, its getter and setter is delegated to Entity class. it mean the truely properties still on the Entity class instead on the Dto class. Therefor when Entity property is change, that change is reflected in DTO delegated property, even when Dto was instantiated before the change. in vice versa when Dto delegated property is change, the change is reflected in Entity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6463b7a801" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>