<?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 Jo Lam on Medium]]></title>
        <description><![CDATA[Stories by Jo Lam on Medium]]></description>
        <link>https://medium.com/@jolam168?source=rss-da3dde6c6635------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nZ8ZGgpqECpaQwJX.</url>
            <title>Stories by Jo Lam on Medium</title>
            <link>https://medium.com/@jolam168?source=rss-da3dde6c6635------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jolam168/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[ Building Android AI Agents with Koog — The Kotlin AI Framework]]></title>
            <link>https://medium.com/@jolam168/building-android-ai-agents-with-koog-the-kotlin-ai-framework-6379ff9dbdff?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/6379ff9dbdff</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 02:31:52 GMT</pubDate>
            <atom:updated>2025-08-02T02:31:52.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>🤖 Building Android AI Agents with Koog — The Kotlin AI Framework</h3><p>Artificial Intelligence is transforming how mobile apps interact with users. From voice assistants to intelligent automation, modern apps are becoming smarter and more helpful.</p><p>If you’re developing Android apps and want to add AI-powered agents to enhance user experience, meet <strong>Koog</strong> — a Kotlin-first AI framework built for native intelligence.</p><p>In this post, I’ll walk you through what Koog is, how it works, how to integrate it into your Android app, and a hands-on example of creating a context-aware wellness assistant.</p><h3>🧠 What is Koog?</h3><p><strong>Koog</strong> is a lightweight, Kotlin-based framework for building intelligent agents on Android or the JVM. Inspired by agent-based modeling, Koog makes it easy to implement goal-driven, decision-making behavior using idiomatic Kotlin.</p><p>With Koog, you can:</p><ul><li>Model an agent’s beliefs, goals, and actions</li><li>React to perception inputs (e.g., user activity, voice commands)</li><li>Reason about goals and make decisions</li><li>Execute actions autonomously</li></ul><p>At its core, Koog agents operate on a <strong>Perception → Cognition → Action</strong> loop — perfect for Android apps needing intelligent behavior without heavy ML overhead.</p><h3>⚙️ Setting Up Koog in Your Android Project</h3><p>Koog is currently distributed via GitHub or local modules. To get started:</p><h3>Step 1: Clone or Add Koog</h3><p>If Koog is not yet on Maven Central, include it as a Git submodule or local library:</p><p><strong>Option A: Local Module</strong></p><pre>git clone https://github.com/yourusername/koog.git</pre><p>Then in settings.gradle.kts:</p><pre>include(&quot;:koog&quot;)<br>project(&quot;:koog&quot;).projectDir = File(&quot;../koog&quot;)</pre><p>And in your build.gradle.kts:</p><pre>dependencies {<br>    implementation(project(&quot;:koog&quot;))<br>}</pre><p><strong>Option B: Via Maven (if published)</strong></p><pre>dependencies {<br>    implementation(&quot;dev.koog:koog-core:1.0.0&quot;)<br>}</pre><h3>Step 2: Initialize Your First Koog Agent</h3><p>Here’s a minimal Koog agent that reminds users to hydrate every hour:</p><pre>val hydrationAgent = KoogAgent {<br>    perception { input -&gt;<br>        if (input == &quot;1_hour_passed&quot;) {<br>            addBelief(&quot;timeToHydrate&quot;)<br>            adoptGoal(&quot;RemindUserToDrinkWater&quot;)<br>        }<br>    }</pre><pre>    cognition {<br>        decisionLogic { goals -&gt;<br>            goals.filter { it.name == &quot;RemindUserToDrinkWater&quot; }<br>        }<br>    }</pre><pre>    action { goal -&gt;<br>        if (goal.name == &quot;RemindUserToDrinkWater&quot;) {<br>            showNotification(&quot;💧 Time to hydrate!&quot;)<br>        }<br>    }<br>}</pre><p>Call this agent’s perception input from anywhere — a timer, WorkManager, or a BroadcastReceiver:</p><pre>// Triggered every hour<br>hydrationAgent.perceive(&quot;1_hour_passed&quot;)</pre><h3>📱 Android Use Case: Context-Aware Wellness Assistant</h3><p>Let’s take it further. Imagine an Android app that encourages users to stand up after sitting too long.</p><pre>val wellnessAgent = KoogAgent {<br>    perception { input -&gt;<br>        if (input == &quot;userSittingTooLong&quot;) {<br>            addBelief(&quot;userIsSedentary&quot;)<br>            adoptGoal(&quot;PromptMovement&quot;)<br>        }<br>    }</pre><pre>    cognition {<br>        decisionLogic { goals -&gt;<br>            goals.filter { it.name == &quot;PromptMovement&quot; }<br>        }<br>    }</pre><pre>    action { goal -&gt;<br>        if (goal.name == &quot;PromptMovement&quot;) {<br>            showNotification(&quot;🧍 Time to stretch! You’ve been sitting for a while.&quot;)<br>        }<br>    }<br>}</pre><p>Hook this up with Google’s <strong>Activity Recognition API</strong> or a timer:</p><pre>activityRecognitionClient<br>    .onStillDetectedFor(minutes = 60) {<br>        wellnessAgent.perceive(&quot;userSittingTooLong&quot;)<br>    }</pre><h3>💡 Why Use Koog?</h3><ul><li><strong>Kotlin-first</strong>: DSL designed with Kotlin idioms in mind.</li><li><strong>No ML Required</strong>: Rule-based cognition without heavy model dependencies.</li><li><strong>Modular Thinking</strong>: Clean separation of perception, cognition, and action.</li><li><strong>Extendable</strong>: Integrate with MLKit, OpenAI APIs, or custom voice commands.</li></ul><p>Koog gives you the flexibility of AI thinking without the weight of full-blown neural networks.</p><h3>🚀 What’s Next?</h3><p>Here are some ideas you can try with Koog:</p><ul><li>Integrate voice commands to trigger goals</li><li>Use sensors (motion, light, location) to drive behavior</li><li>Add LLM-powered goal reasoning via OpenAI or Gemini</li><li>Chain agents together for multi-goal assistants</li></ul><p>Koog is a fresh take on embedded AI for mobile apps — not bloated, not overly complex. Just intelligent behavior, the Kotlin way.</p><p>If you’re excited about bringing smart, decision-making agents into your Android apps, Koog gives you the tools to start today.</p><p>Happy building! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6379ff9dbdff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ ASI‑ARCH：AI 研究的「第 37 步」突破？解密人工超智能的架構發現系統]]></title>
            <link>https://medium.com/@jolam168/asi-arch-ai-%E7%A0%94%E7%A9%B6%E7%9A%84-%E7%AC%AC-37-%E6%AD%A5-%E7%AA%81%E7%A0%B4-%E8%A7%A3%E5%AF%86%E4%BA%BA%E5%B7%A5%E8%B6%85%E6%99%BA%E8%83%BD%E7%9A%84%E6%9E%B6%E6%A7%8B%E7%99%BC%E7%8F%BE%E7%B3%BB%E7%B5%B1-d01a83883a31?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01a83883a31</guid>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 07:05:33 GMT</pubDate>
            <atom:updated>2025-07-28T07:05:33.209Z</atom:updated>
            <content:encoded><![CDATA[<p>在 2024–2025 年 AI 領域出現了一個引發討論的名字：<strong>ASI‑ARCH</strong>。這個由 GAIR-Lab 團隊開發的系統，聲稱透過人工超智能（ASI）架構，自主發現並驗證了一系列創新神經網絡結構。它的誕生甚至被比喻為「AI 研究的 AlphaGo 第 37 步」。</p><p>這篇文章將快速帶你了解什麼是 ASI‑ARCH、它為何受矚目、需要多少算力，以及你若想複製這類研究，會花多少錢。</p><h3>💡 ASI‑ARCH 是什麼？</h3><p><strong>ASI‑ARCH（Artificial Superintelligence Architecture Discovery）</strong> 是一個開源 AI 系統，目的是讓 AI 自己設計新的 AI 模型架構。簡單來說，這是一個 AI 為自己發現「最聰明版本」的研究流程。</p><p>這個系統由多個 AI 代理人（Agents）組成，每個代理負責不同任務：提出架構假設、撰寫代碼、訓練模型、分析結果，最後將表現好的架構納入資料庫，供後續參考與優化。</p><p>在一次大型實驗中，它：</p><ul><li>自主執行了 <strong>1,773 次架構設計實驗</strong></li><li>消耗了 <strong>約 20,000 GPU 小時</strong></li><li>發現了 <strong>106 種表現超越基準的線性注意力架構</strong></li></ul><h3>🧠 為何被稱為「AI 的 AlphaGo 第 37 步」？</h3><p>如果你還記得 2016 年 AlphaGo 對戰李世乭時的「第 37 手」 — — 那是一次出乎所有人意料、卻極具創造力的落子，完全跳脫人類的圍棋直覺。</p><p>ASI‑ARCH 發現的某些神經網絡架構，也同樣跳出了人類設計的慣性。這讓部分研究者認為，它是 <strong>AI 創造力在模型設計上的首次具體展現</strong>，猶如當年 AlphaGo 的「神之一手」。</p><h3>⚙️ 需要多少算力？能不能複製？</h3><p>根據官方論文與 GitHub 文件，ASI‑ARCH 所需資源如下：</p><ul><li><strong>總算力</strong>：約 20,000 GPU 小時</li><li><strong>主機設備</strong>：多數基於 V100 / A100 等高效能 GPU</li><li><strong>系統架構</strong>：多代理架構 + MongoDB + LLM Agent + RAG 系統</li></ul><p>如果你打算在雲端複製此研究，按每小時 $2.5–$3.5 美元計算：</p><p>GPU 型號單位價格（USD）20,000 小時總成本NVIDIA V100約 $2.50約 $50,000NVIDIA A100約 $3.50約 $70,000</p><p>👉 不含儲存、網路與維運成本。</p><h3>💰 有可能更便宜嗎？</h3><p>是的。你可以透過以下方式降低實驗成本：</p><ul><li><strong>使用預留型 / 長期雲資源折扣</strong></li><li><strong>在 Oracle、Lambda Labs 等價格較低的平台租用 GPU</strong></li><li><strong>考慮使用去中心化算力平台（如 ASI Compute）</strong></li><li><strong>加入開源協作團隊，共享資源</strong></li></ul><h3>🔚 結語：突破還是話術？</h3><p>雖然 ASI‑ARCH 提供的架構在某些任務上確實表現優異，但許多評論者也指出，它目前的成果屬於「增量優化」而非「根本顛覆」。也就是說，它可能還不是我們真正期待的「超智能」，但它展示了一條可能走向那個方向的路。</p><p>未來，這類自主 AI 研究系統可能成為加速模型創新的關鍵工具，尤其對於中小型研究團隊而言，意義重大。</p><h3>📚 參考來源</h3><ul><li>論文：<a href="https://arxiv.org/abs/2507.18074">https://arxiv.org/abs/2507.18074</a></li><li>GitHub 專案頁：<a href="https://github.com/GAIR-NLP/ASI-Arch">https://github.com/GAIR-NLP/ASI-Arch</a></li><li>YouTube 解說影片：<a href="https://www.youtube.com/watch?v=prbG-AfFJCY">https://www.youtube.com/watch?v=prbG-AfFJCY</a></li><li>DeepLearning Reddit 討論：<a href="https://www.reddit.com/r/deeplearning/comments/1ma97e9">https://www.reddit.com/r/deeplearning/comments/1ma97e9</a></li><li>Singularity Reddit 討論：<a href="https://www.reddit.com/r/singularity/comments/1mafu6i">https://www.reddit.com/r/singularity/comments/1mafu6i</a></li><li>AlphaGo 第 37 手解析：https://en.wikipedia.org/wiki/AlphaGo_versus_Lee_Sedol</li><li>雲端價格參考：https://cloud.google.com/compute/all-pricing</li><li>Oracle GPU 定價：<a href="https://www.oracle.com/cloud/compute/pricing">https://www.oracle.com/cloud/compute/pricing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01a83883a31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android : From callback hell to coroutine]]></title>
            <link>https://medium.com/@jolam168/android-from-callback-hell-to-coroutine-bbb3531eee8c?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb3531eee8c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 03:07:15 GMT</pubDate>
            <atom:updated>2025-03-29T03:07:15.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android : From callback hell to coroutine</h3><p>Below is a blog-style summary that explains how to refactor an API call from a callback-based method to a coroutine-based method using a generic example.</p><h3>Refactoring API Calls from Callbacks to Coroutines in Kotlin</h3><p>When building Android apps, you’ll often need to make network requests or other asynchronous API calls. Traditionally, many APIs rely on callbacks to deliver their results, which can lead to deeply nested code and make error handling more challenging. Fortunately, Kotlin’s coroutines provide a cleaner, more sequential way to write asynchronous code.</p><p>In this blog post, we’ll walk through refactoring an API call that uses callbacks into a coroutine-based approach. For this example, we’ll use a generic API call named fetchData instead of specific keywords like &quot;settle&quot; or &quot;transaction.&quot;</p><h3>Callback-Based API Call</h3><p>Imagine you have an API that fetches data from a network using a callback interface:</p><pre>interface DataCallback&lt;T&gt; {<br>    fun onSuccess(data: T)<br>    fun onError(code: Int, message: String)<br>}</pre><pre>fun fetchData(amount: String, installments: String, qrCode: String, callback: DataCallback&lt;ResponseData&gt;) {<br>    // Simulate network call...<br>    // This function calls either callback.onSuccess(data) or callback.onError(code, message)<br>}</pre><p>Using this approach, you’d need to implement the callback each time you call fetchData. This can lead to callback hell and makes it harder to reason about the control flow.</p><h3>Refactoring to Coroutines</h3><p>By refactoring the callback-based API call into a suspend function, you can write asynchronous code in a sequential style. You can wrap the callback in a suspend function using suspendCoroutine (or suspendCancellableCoroutine if needed).</p><h3>The Suspend Wrapper</h3><p>Here’s how you can wrap the fetchData callback API into a suspend function:</p><pre>suspend fun fetchDataAsync(<br>    amount: String,<br>    installments: String,<br>    qrCode: String<br>): APIResult&lt;ResponseData&gt; = suspendCoroutine { cont -&gt;<br>    fetchData(amount, installments, qrCode, object : DataCallback&lt;ResponseData&gt; {<br>        override fun onSuccess(data: ResponseData) {<br>            cont.resume(APIResult.Success(data))<br>        }<br>        override fun onError(code: Int, message: String) {<br>            cont.resume(APIResult.Failure(code, message))<br>        }<br>    })<br>}</pre><p>In this code:</p><ul><li>We wrap the callback in a suspend function called fetchDataAsync.</li><li>We use suspendCoroutine to suspend the coroutine until the API call completes.</li><li>Depending on whether the API call is successful or not, we resume the coroutine with either a success or failure result.</li></ul><h3>Using the Suspend Function</h3><p>Once you have a suspend version of your API call, you can call it from within a coroutine scope, which leads to clearer, sequential logic:</p><pre>fun performDataOperation(amount: String, installments: String, qrCode: String) {<br>    viewModelScope.launch {<br>        showLoader()<br>        val result = withContext(Dispatchers.IO) {<br>            fetchDataAsync(amount, installments, qrCode)<br>        }<br>        when (result) {<br>            is APIResult.Success -&gt; {<br>                // Process successful response<br>                _dataResult.postValue(result.data)<br>            }<br>            is APIResult.Failure -&gt; {<br>                // Handle error response<br>                _isFailed.postValue(true to result.msg)<br>            }<br>        }<br>        hideLoader()<br>    }<br>}</pre><h3>Benefits of Using Coroutines</h3><p><strong>Sequential Style:</strong><br> Code reads like synchronous code, making it easier to follow the logic.</p><p><strong>Better Error Handling:</strong><br> Use try-catch blocks to handle errors in one place, rather than dealing with nested callbacks.</p><p><strong>Non-Blocking:</strong><br> Coroutines ensure that long-running tasks (such as network calls) do not block the main thread, keeping your UI responsive.</p><p><strong>Structured Concurrency:</strong><br> Coroutines enable you to structure your asynchronous code with clear scopes (using viewModelScope, for example), making cancellation and error propagation much more manageable.</p><h3>Conclusion</h3><p>Refactoring from callbacks to coroutines simplifies asynchronous API calls. It allows you to write clear, sequential code that’s easy to maintain and understand. With coroutines, you wrap your callback-based APIs into suspend functions and then use coroutine builders like launch and withContext to perform your operations without blocking the main thread.</p><p>By making this transition, you improve the readability and maintainability of your code, while leveraging Kotlin’s powerful concurrency features.</p><p>Happy coding!</p><ul><li><a href="https://outcomeschool.com/blog/callback-to-coroutines-in-kotlin">Callback to Coroutines in Kotlin</a></li><li><a href="https://www.spread1.co.jp/wp/post-2749/">【kotlin】コールバックパターンの処理をsuspend関数に変換し、直列的に扱う | ブログ - 株式会社スプレッドワン</a></li><li><a href="https://qiita.com/kaba/items/355363645b8a9e47e2da">３分で理解する coroutine + retrofit2 - Qiita</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb3531eee8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If your project does not contain any PendingIntent but you’re still experiencing a crash, WAIT!]]></title>
            <link>https://medium.com/@jolam168/if-your-project-does-not-contain-any-pendingintent-but-youre-still-experiencing-a-crash-wait-178d6a661db4?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/178d6a661db4</guid>
            <category><![CDATA[pendingintent]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[fcm]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 06:33:46 GMT</pubDate>
            <atom:updated>2025-03-14T06:36:51.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Eu6snsMm7Ms2Bj_v" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>If your <strong>project does not contain any </strong><strong>PendingIntent</strong> but you’re still experiencing a <strong>crash, WAIT! that is not your fault!</strong></h3><h3>The error causes the crash👇</h3><blockquote>Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.</blockquote><p>If your <strong>project does not contain any </strong><strong>PendingIntent</strong> but you’re still experiencing a <strong>crash when receiving Firebase Cloud Messaging (FCM) notifications in the background</strong>, then Firebase is likely using an <strong>implicit </strong><strong>PendingIntent internally</strong> when handling notifications.</p><ul><li>When <strong>FCM delivers a </strong><strong>notification payload</strong>, Firebase <strong>automatically</strong> creates and displays a system notification.</li><li>In <strong>Android 12+ (API 31+)</strong>, Firebase <strong>internally</strong> creates a PendingIntent, but it fails because it does <strong>not</strong> include FLAG_IMMUTABLE.</li><li>If your app <strong>doesn’t handle the notification manually</strong>, Firebase <strong>defaults to its internal notification system, which crashes</strong>.</li></ul><p>If you’re sending FCM from your backend <strong>(Rails, Postman, Firebase API, etc.)</strong>, make sure you’re using a <strong>data payload instead of a </strong><strong>notification payload</strong>.</p><h3>❌ Wrong Payload (Only notification)</h3><p>This will <strong>crash in background</strong> because Firebase tries to show a system notification:</p><pre>{<br>  &quot;to&quot;: &quot;YOUR_DEVICE_TOKEN&quot;,<br>  &quot;notification&quot;: {<br>    &quot;title&quot;: &quot;Hello!&quot;,<br>    &quot;body&quot;: &quot;This will cause issues in background mode!&quot;<br>  }<br>}</pre><h3>✅ Correct Payload (Using data Instead)</h3><p>Use this format instead:</p><pre>{<br>  &quot;to&quot;: &quot;YOUR_DEVICE_TOKEN&quot;,<br>  &quot;data&quot;: {<br>    &quot;title&quot;: &quot;Hello!&quot;,<br>    &quot;body&quot;: &quot;This works in background mode!&quot;<br>  }<br>}</pre><p>💡 <strong>Why?</strong></p><ul><li><strong>data payload ensures that </strong><strong>onMessageReceived() is called</strong>, allowing you to manually handle the notification.</li><li>Firebase <strong>won’t create a system-level notification</strong>, avoiding the issue with PendingIntent.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=178d6a661db4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiveData or Flow : Which to chooi]]></title>
            <link>https://medium.com/@jolam168/livedata-or-flow-which-to-chooi-e3a44acb157c?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a44acb157c</guid>
            <category><![CDATA[koltin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 05:23:10 GMT</pubDate>
            <atom:updated>2023-06-24T05:23:10.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>LiveData or Flow : Which to choose?</h3><p>LiveData and Flow are both important parts of the Android ecosystem that help to manage streams of data in a lifecycle-aware way. They have different strengths and use cases, and understanding these can help you choose the right tool for the job.</p><p>- LiveData is a lifecycle-aware data holder. It means that LiveData respects the lifecycle of other app components, such as activities, fragments, or services.<br>- LiveData is observed and it only notifies active lifecycle owners. This makes LiveData an excellent choice for anything that requires UI updates.<br>- LiveData can be observed from the main thread and it ensures that the observable data is always up-to-date.<br>- LiveData is very easy to use with Android UI components and it integrates well with ViewModel.</p><p>Let’s say we have an app that fetches the user’s location and displays it on the UI. LiveData is a good choice for this because we only want to update the UI when the user is actively using the app.</p><pre><br>val locationLiveData: MutableLiveData&lt;Location&gt; = LocationLiveData(context)<br>locationLiveData.observe(this, Observer { location -&gt;<br> // Update UI.<br>})<br>```</pre><p>- Flow is part of Kotlin Coroutines. It’s a cold asynchronous data stream, which means it does not run or emit items until a collector starts to collect.<br>- Flow can emit multiple values and can be transformed and composed with operators.<br>- Flow can be collected on any coroutine context, not just on the main thread.<br>- Flow requires more understanding of coroutines and is more powerful and flexible than LiveData.</p><p>Example use case for Flow:</p><p>Suppose we have an app that fetches a continuous stream of sensor data, does some processing on it, and then stores the processed data in a database. Flow is a good choice for this because we can apply transformations to the data and switch threads as needed.</p><pre>val sensorDataFlow: Flow&lt;SensorData&gt; = sensorManager.sensorDataFlow()<br>sensorDataFlow<br> .map { processData(it) } // Process data on default dispatcher.<br> .flowOn(Dispatchers.Default) <br> .onEach { storeData(it) } // Store data on IO dispatcher.<br> .flowOn(Dispatchers.IO) <br> .catch { e -&gt; logError(e) } // Handle errors.<br> .launchIn(scope) // Start collecting.<br>```</pre><p>LiveData is a good choice when dealing with lifecycle-bound UI updates, while Flow is a more powerful and flexible tool that can handle complex data processing and manipulation. However, it’s also possible to use LiveData and Flow together to take advantage of the strengths of both. For example, you could use Flow to handle data processing, and then convert the Flow to LiveData to update the UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a44acb157c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jackpack Compose: Reasons to Recommend It for New App Development]]></title>
            <link>https://medium.com/@jolam168/jackpack-compose-reasons-to-recommend-it-for-new-app-development-e8a7c4f35e19?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8a7c4f35e19</guid>
            <category><![CDATA[jackpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Fri, 26 May 2023 11:36:19 GMT</pubDate>
            <atom:updated>2023-05-26T11:36:35.709Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern app development, having an efficient and flexible UI development framework is essential. That’s where Jetpack Compose comes into the picture. Jetpack Compose is a modern and powerful toolkit for building the user interface (UI) of Android applications. In this article, we will explore why Jetpack Compose is recommended for new app development.</p><p>1. Declarative UI:<br>Jetpack Compose adopts a declarative UI approach, meaning the appearance and behavior of the UI are managed in a centralized manner. Unlike traditional UI frameworks, where managing UI states and interactions can become complex, Jetpack Compose automatically recomposes the UI based on state changes. This improves code maintainability, readability, and speeds up the development process.</p><p>Example:</p><pre><br>@Composable<br>fun Greeting(name: String) {<br> Text(text = “Hello, $name!”)<br>}<br></pre><p>2. Modern Development Experience:<br>Jetpack Compose is developed using the Kotlin language, providing a modern development experience. Kotlin is a more concise and expressive language compared to Java, and it seamlessly integrates with Jetpack Compose. Additionally, Kotlin offers features like compile-time type safety and null safety, enhancing developer productivity.</p><p>Example:</p><pre><br>val message: String? = null<br>message?.let {<br> // Code block executed only if ‘message’ is not null<br> println(message)<br>}<br></pre><p>3. Hot Reload:<br>Jetpack Compose supports hot reload, allowing instant reflection of code changes. By eliminating the need for app rebuilding and restarting, developers can quickly see the effects of their changes. This enables rapid prototyping and debugging.</p><p>Example: Making changes to the UI code and immediately seeing the updated UI without restarting the app.</p><p>4. Integrated Animation Support:<br>Jetpack Compose provides integrated tools and APIs for animation support. Animation is crucial for enhancing the user experience, and with Jetpack Compose’s animation features, developers can create smooth and visually appealing app transitions and interactions.</p><p>Example: Defining an animated transition between two states of a UI element.</p><pre>val size by animateDpAsState(targetValue = if (expanded) 200.dp else 100.dp)<br>Box(<br> Modifier.size(size).background(Color.Blue)<br>)<br></pre><p>5. Platform Support:<br>Jetpack Compose is fully integrated with the latest versions of Android and optimized for Android app development. Furthermore, there are plans to support multi-platform development, allowing the use of Jetpack Compose on platforms like iOS and the web in the future.</p><p>Conclusion:<br>Jetpack Compose offers numerous advantages for new app development, including declarative UI, modern development experience, hot reload, integrated animation support, and platform compatibility. These features enable developers to create more efficient and flexible applications. It is expected that Jetpack Compose will become the mainstream approach for Android app development. Consider exploring Jetpack Compose for your future app development projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8a7c4f35e19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding BackStackEntry in Android: Managing Fragment Navigation History]]></title>
            <link>https://medium.com/@jolam168/understanding-backstackentry-in-android-managing-fragment-navigation-history-6015a0ef7790?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/6015a0ef7790</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Tue, 16 May 2023 01:43:27 GMT</pubDate>
            <atom:updated>2023-05-16T01:43:27.918Z</atom:updated>
            <content:encoded><![CDATA[<p>In Android, a `BackStackEntry` represents an entry in the back stack of a `FragmentManager`. The back stack is used to manage the navigation history of fragments within an activity. It allows users to navigate back to previous fragments by pressing the back button or by using other navigation mechanisms.</p><p>Each time a fragment transaction occurs, such as adding, replacing, or removing a fragment, a new entry is created and added to the back stack. This entry keeps track of the transaction and allows the user to navigate back to the previous state of the fragment.</p><p>Here’s an example to illustrate the usage of `BackStackEntry`:</p><pre>// Adding a fragment transaction to the back stack<br>FragmentManager fragmentManager = getSupportFragmentManager();<br>FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();ExampleFragment fragment = new ExampleFragment();<br>fragmentTransaction.replace(R.id.container, fragment);<br>fragmentTransaction.addToBackStack(“example_fragment”); // Adding the transaction to the back stack with a name<br>fragmentTransaction.commit();<br></pre><p>In the code snippet above, a new instance of `ExampleFragment` is created and a transaction is initiated using the `FragmentManager`. The `replace` method is used to replace an existing fragment in the container with the new fragment. Then, `addToBackStack` is called with the name `”example_fragment”`, which adds the transaction to the back stack with the specified name.</p><p>Later, when the user presses the back button, the `FragmentManager` automatically pops the top entry from the back stack and restores the previous state of the fragment. You can listen for back stack changes using a `BackStackListener` to perform additional actions when a fragment is popped from the back stack.</p><pre><br>// Listening for back stack changes<br>FragmentManager fragmentManager = getSupportFragmentManager();<br>fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {<br>   @Override<br>   public void onBackStackChanged() {<br>   int backStackEntryCount = fragmentManager.getBackStackEntryCount();<br>   if (backStackEntryCount &gt; 0) {<br>   FragmentManager.BackStackEntry backStackEntry = fragmentManager.getBackStackEntryAt(backStackEntryCount — 1);<br>   String fragmentName = backStackEntry.getName();<br>   // Perform additional actions based on the fragment name<br>   }<br> }<br>});<br></pre><p>In this example, we add an `OnBackStackChangedListener` to the `FragmentManager` to listen for back stack changes. When the back stack changes, we retrieve the top entry using `getBackStackEntryAt` and extract the name of the fragment transaction using `getName()`. You can perform additional actions based on the fragment name, such as updating the UI or handling specific navigation scenarios.</p><p>By utilizing `BackStackEntry`, you can implement flexible and intuitive navigation within your Android application by managing the fragment back stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6015a0ef7790" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Reasons Why Operator Functions in Kotlin Are Better]]></title>
            <link>https://medium.com/@jolam168/4-reasons-why-operator-functions-in-kotlin-are-better-6644c5dbdd80?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/6644c5dbdd80</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Wed, 03 May 2023 05:41:33 GMT</pubDate>
            <atom:updated>2023-05-03T05:41:33.831Z</atom:updated>
            <content:encoded><![CDATA[<p>Using operator functions in Kotlin is a powerful feature that can provide several benefits over using traditional operator syntax for integer addition. Here are some examples of how operator functions can improve your code:</p><p>1.Custom operator behavior:</p><p>By overloading operator functions, you can define your own behavior for operators that goes beyond their default functionality. For example, let’s say you have a class Person with a name property of type String, and you want to define an operator function that concatenates two Person objects&#39; names:</p><pre>data class Person(val name: String) {<br>    operator fun plus(other: Person): String {<br>        return &quot;${this.name} and ${other.name}&quot;<br>    }<br>}</pre><p>Now you can concatenate two Person objects&#39; names using the + operator:</p><pre>val person1 = Person(&quot;John&quot;)<br>val person2 = Person(&quot;Jane&quot;)<br>val result = person1 + person2<br>println(result) // Output: John and Jane</pre><p>2.Avoiding type errors:</p><p>Defining operator functions with specific input and output types can prevent type errors that can occur when using the traditional operator syntax. For example, let’s say you have a class Point with x and y properties of type Int, and you want to define an operator function that adds two Point objects:</p><pre>data class Point(val x: Int, val y: Int) {<br>    operator fun plus(other: Point): Point {<br>        return Point(this.x + other.x, this.y + other.y)<br>    }<br>}</pre><p>Now you can add two Point objects using the + operator, and the result will be another Point object:</p><pre>val point1 = Point(1, 2)<br>val point2 = Point(3, 4)<br>val result = point1 + point2<br>println(result) // Output: Point(x=4, y=6)</pre><p>3.Readability and clarity:</p><p>By defining operator functions, you can make your code more readable and clear. For example, let’s say you have a class ComplexNumber with real and imaginary properties of type Double, and you want to define an operator function that adds two ComplexNumber objects:</p><pre>data class ComplexNumber(val real: Double, val imaginary: Double) {<br>    operator fun plus(other: ComplexNumber): ComplexNumber {<br>        return ComplexNumber(this.real + other.real, this.imaginary + other.imaginary)<br>    }<br>}</pre><p>Now you can add two ComplexNumber objects using the + operator, and the result will be another ComplexNumber object:</p><pre>val num1 = ComplexNumber(1.0, 2.0)<br>val num2 = ComplexNumber(3.0, 4.0)<br>val result = num1 + num2<br>println(result) // Output: ComplexNumber(real=4.0, imaginary=6.0)</pre><p>4.Encapsulation:</p><p>Operator functions can be defined within a class or object, which allows you to encapsulate your operator behavior within a specific context. For example, let’s say you have a class Fraction with numerator and denominator properties of type Int, and you want to define an operator function that adds two Fraction objects:</p><pre>class Fraction(val numerator: Int, val denominator: Int) {<br>    operator fun plus(other: Fraction): Fraction {<br>        val newNumerator = this.numerator * other.denominator + other.numerator * this.denominator<br>        val newDenominator = this.denominator * other.denominator</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6644c5dbdd80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Code for Preventing Double-Click Button]]></title>
            <link>https://medium.com/@jolam168/kotlin-code-for-preventing-double-click-button-9dc39852dfb?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc39852dfb</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 07:17:12 GMT</pubDate>
            <atom:updated>2023-04-27T07:17:12.798Z</atom:updated>
            <content:encoded><![CDATA[<p>The funny thing is if you are using Android Jetpack’s Navigation component in your project, double tap the button that involve screen change aka navigation quickly will crash your app. To prevent this in robust way:</p><pre>private var lastClickTime: Long = 0<br><br>button.setOnClickListener {<br>    val currentTime = System.currentTimeMillis()<br>    if (currentTime - lastClickTime &gt; 1000) { // Set the minimum click interval to 1 second<br>        // Perform the button action here<br>    }<br>    lastClickTime = currentTime<br>}</pre><p>This code uses a variable lastClickTime to store the timestamp of the last button click. When the button is clicked again, the code checks if the time elapsed since the last click is greater than the minimum click interval (1 second in this case). If it is, the button action is performed and lastClickTime is updated to the current time.</p><p>By using this approach, the code prevents the button from being clicked too quickly in succession, which can help prevent unintended actions or errors caused by rapid clicks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc39852dfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin’s Common Mistakes You Should Avoid]]></title>
            <link>https://medium.com/@jolam168/kotlins-common-mistakes-you-should-avoid-e3537dc41a58?source=rss-da3dde6c6635------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3537dc41a58</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jo Lam]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 07:42:06 GMT</pubDate>
            <atom:updated>2023-04-25T07:42:06.565Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Misusing Nullability: Kotlin has a strong null-safety system, and developers need to be careful when dealing with nullability. One common mistake is to assume that a variable is not null, causing a NullPointerException at runtime.</li></ol><pre>var name: String? = null<br>println(name.length) // This will cause a NullPointerException</pre><p>To avoid this mistake, use safe call operator or null checks to ensure that the variable is not null:</p><pre>var name: String? = null<br>println(name?.length) // This will print null</pre><p>2. Using ‘!!’ Operator: The ‘!!’ operator is used to force nullability, and it can cause a NullPointerException if the object is actually null. This operator should be used sparingly, and only when the developer is absolutely certain that the object is not null.</p><pre>var name: String? = null<br>println(name!!.length) // This will cause a NullPointerException</pre><p>To avoid this mistake, use safe call operator or null checks to ensure that the variable is not null:</p><pre>var name: String? = null<br>println(name?.length) // This will print null</pre><p>3. Not Using Data Classes: Kotlin has a built-in feature called data classes that automatically generate getters, setters, equals, hashCode, and toString methods. Data classes can simplify code and reduce the risk of errors.</p><pre>data class Person(val name: String, val age: Int)</pre><p>To create an instance of this data class:</p><pre>val person = Person(&quot;John&quot;, 30)</pre><p>4. Not Using Extension Functions: Kotlin allows developers to add methods to existing classes using extension functions. Extension functions can simplify code and make it more readable.</p><pre>fun String.isEmail(): Boolean {<br>    val emailRegex = Regex(&quot;[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}&quot;)<br>    return emailRegex.matches(this)<br>}</pre><p>To use this extension function:</p><pre>val email = &quot;example@mail.com&quot;<br>if (email.isEmail()) {<br>    println(&quot;Valid email&quot;)<br>} else {<br>    println(&quot;Invalid email&quot;)<br>}</pre><p>5. Using Mutable Variables Everywhere: Kotlin has both mutable and immutable variables. Mutable variables can be changed after they are initialized, while immutable variables cannot. Developers should use immutable variables whenever possible, as they are safer and can help prevent bugs.</p><pre>val pi = 3.14 // immutable variable<br>var counter = 0 // mutable variable</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3537dc41a58" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>