<?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 Computational Everything on Medium]]></title>
        <description><![CDATA[Stories by Computational Everything on Medium]]></description>
        <link>https://medium.com/@jameskong_35184?source=rss-99992030b507------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w0qOjDfBdrEqUBrwItWbvQ@2x.jpeg</url>
            <title>Stories by Computational Everything on Medium</title>
            <link>https://medium.com/@jameskong_35184?source=rss-99992030b507------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 13:05:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jameskong_35184/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[AI 編程的三個致命錯覺：從 OpenCode 看工程判斷力的回歸]]></title>
            <link>https://medium.com/@jameskong_35184/ai-%E7%B7%A8%E7%A8%8B%E7%9A%84%E4%B8%89%E5%80%8B%E8%87%B4%E5%91%BD%E9%8C%AF%E8%A6%BA-%E5%BE%9E-opencode-%E7%9C%8B%E5%B7%A5%E7%A8%8B%E5%88%A4%E6%96%B7%E5%8A%9B%E7%9A%84%E5%9B%9E%E6%AD%B8-e1d27874ec5d?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d27874ec5d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[hong-kong]]></category>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 21:48:23 GMT</pubDate>
            <atom:updated>2026-08-08T21:48:23.285Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>AI 編程的三個致命錯覺：從 OpenCode 看工程判斷力的回歸</strong></blockquote><p>AI 讓「把東西做出來」越來越便宜，但沒有讓我們更容易判斷「應該做甚麼」。OpenCode 是近年增長最快的 AI coding tools 之一。它的聯合創辦人 Dax Raad，卻沒有像很多 AI 工具創辦人那樣，強調模型有多聰明、工程效率可以提升多少倍。</p><p>相反，他提出了一個更令人不安的觀察：</p><blockquote>AI 讓寫程式變得更容易，但最困難的部分 — — 判斷做甚麼、為甚麼做，以及做完是否值得維護 — — 並沒有消失。這個觀察不只適用於 AI 編程工具，也適用於所有正在引入 AI agent 的企業。</blockquote><h3><strong>OpenCode 的故事，不只是「另一個 AI Coding Agent」</strong></h3><p>OpenCode 的核心定位不是訓練一個比別人更聰明的模型，而是成為一個：</p><p>- 開源的 coding harness；</p><p>- 模型供應商之間的中立層；</p><p>- 開發者與企業治理之間的控制層。</p><p>在 Anthropic、OpenAI 及其他模型供應商競爭的市場中，OpenCode 選擇不押注於單一模型，而是站在中間，讓開發者可以使用不同的模型和服務。</p><p>這個定位令它受益於上游競爭：</p><blockquote>模型供應商互相競爭</blockquote><blockquote>↓</blockquote><blockquote>開發者需要中立工具</blockquote><blockquote>↓</blockquote><blockquote>OpenCode 成為分發和整合層</blockquote><p>這與 Dax 早期參與的 SST / OpenNext 有相似之處。</p><p>OpenNext 解決的是 Next.js 在 Vercel 以外的部署需求：開發者想使用 AWS 等其他平台，但原有生態並沒有很好地支援這個路徑。OpenNext 便填補了這個結構性空位。</p><p>這不是從零創造一個新類別，而是連接兩個原本沒有良好溝通的生態。</p><p>這也是許多真正有價值的 startup opportunity 的來源。</p><h3><strong>第一個致命錯覺：寫程式更快，等於產品開發更快</strong></h3><p>AI coding tools 最容易銷售的故事是：</p><blockquote>以前工程師需要一星期，現在只需要一天。</blockquote><p>但這個故事忽略了一件事：寫程式只是產品開發的一部分。</p><p>真正困難的工作包括：</p><p>- 決定應該解決哪一個問題；</p><p>- 判斷用戶真正需要甚麼；</p><p>- 知道哪些需求不應該做；</p><p>- 設計合理的產品邊界；</p><p>- 估計長期維護成本；</p><p>- 決定甚麼時候停止增加功能。</p><p>Dax Raad 形容，AI 並沒有令他不用思考。相反，他由大約「95% 思考、5% 執行」，變成「96% 思考、4% 執行」。</p><p>這不是 10 倍生產力，而是執行成本下降了一點，但判斷成本仍然存在。</p><p>更危險的是，錯誤方向現在也變得非常便宜：</p><p>實作成本下降</p><blockquote>→ 嘗試錯誤方向變得容易</blockquote><blockquote>→ 團隊更快地做錯東西</blockquote><blockquote>→ activity 被誤認為 progress</blockquote><p>AI 可以幫助你更快建立一個 prototype，但它不能自動告訴你這個 prototype 是否值得存在。</p><h3><strong>第二個致命錯覺：功能更多，產品就會更好</strong></h3><p>Dax 提到一個常見的產品陷阱：</p><p>- 用戶提出一個問題，就加一個功能；</p><p>- 競爭對手推出一個功能，就跟著加；</p><p>- 團隊有人有一個想法，又加進去；</p><p>- 每個功能都可以由 agent 快速完成。</p><p>最後，產品可能擁有一千個功能，但沒有人說得清楚它到底是甚麼。</p><p>這就是他所說的「Frankenstein product」。</p><p>功能數量增加，不等於產品質素增加。</p><p>每一個功能都會帶來永久成本：</p><p>- 需要維護；</p><p>- 需要測試；</p><p>- 需要文件；</p><p>- 需要支援；</p><p>- 會影響其他功能；</p><p>- 會增加 onboarding 複雜度；</p><p>- 會令產品定位變得模糊。</p><p>因此，AI 時代的產品風險不只是 <strong>code rot</strong>，還包括 <strong>product rot</strong>。</p><p><strong>Code rot</strong></p><p>- 重複邏輯；</p><p>- 隱藏 hack；</p><p>- 不一致的架構；</p><p>- 不斷累積的技術債。</p><p><strong>Product rot</strong></p><p>- onboarding 越來越難；</p><p>- 功能沒有清晰層級；</p><p>- 用戶不知道下一步應該做甚麼；</p><p>- 所有能力都被塞進 command palette；</p><p>- 產品變成一個沒有人整理過的抽屜。</p><p>最重要的一點是：</p><blockquote>AI 可以讓團隊十倍快地增加功能，但不會令團隊擁有十倍多的好想法。</blockquote><p>所以 AI 時代的產品經理和創辦人，反而需要更加重視 restraint — — 克制。</p><p>— -</p><h3><strong>第三個致命錯覺：AI agent 會取代工程判斷</strong></h3><p>AI agent 可以產生程式碼，但它不會自動承擔程式碼的後果。</p><p>過去，工程師親手寫出一個 hack 時，通常會感受到某種心理阻力：</p><blockquote>第一次寫 hack：有點不舒服</blockquote><blockquote>第二次再寫：更加不舒服</blockquote><blockquote>第三次：開始考慮重構</blockquote><p>但當 agent 代替你寫出這些 hack，工程師可能看不到相同的痛苦，也不會立即感受到程式碼正在變差。</p><p>結果是：</p><blockquote>agent 隱藏實作細節</blockquote><blockquote>→ 錯誤回饋變弱</blockquote><blockquote>→ 技術債更容易被忽略</blockquote><blockquote>→ 系統逐漸失去一致性</blockquote><p>這並不代表 AI 會令技術債無法處理。</p><p>事實上，agent 也令大規模重構、測試和模式遷移變得更便宜。</p><p>真正的結論是：</p><blockquote>AI 時代不應該少做重構，而應該比以前做更多重構。</blockquote><p>工程師的角色，會由單純寫程式，逐漸轉移到：</p><p>- 架構判斷；</p><p>- 邊界設計；</p><p>- specification；</p><p>- verification；</p><p>- code review；</p><p>- system invariants；</p><p>- 例外處理；</p><p>- 維護和重構。</p><p>AI 沒有消滅工程判斷力，只是把工程判斷力推到更高的抽象層。</p><h3><strong>Product Taste 不是美學，而是取捨能力</strong></h3><p>Dax Raad 談到的「taste」，不是指介面是否漂亮。</p><p>它更接近以下能力：</p><p>- 知道甚麼應該被突出；</p><p>- 知道甚麼應該被隱藏；</p><p>- 知道甚麼功能應該延遲；</p><p>- 知道甚麼需求不值得滿足；</p><p>- 能夠維持產品的一致性；</p><p>- 能夠拒絕短期但會造成長期負擔的決定。</p><p>在 AI 令 implementation 變得廉價之後，這種判斷力會變得更加重要。</p><p>以前，一個壞想法可能因為太難實作而自然被淘汰。</p><p>現在，一個壞想法可能只需要一個 prompt 就能完成。</p><p>這是 AI 產品開發中一個非常容易被忽略的變化：</p><blockquote>實作摩擦下降之後，產品的自我約束能力就變得更加重要。</blockquote><h3><strong>Anthropic 封禁事件：中立層的力量與脆弱性</strong></h3><p>現有訪談和二次資料描述，Anthropic 曾經限制 Claude Code subscription 在 OpenCode 中的使用。</p><p>事件引發社群反彈，OpenCode 隨後聯絡 OpenAI，而 OpenAI 很快提供支援。這場衝突反而為 OpenCode 帶來大量關注和用戶增長。</p><p>這件事反映出中立層的雙重價值。</p><p><strong>中立層的力量</strong></p><p>當多個上游供應商互相競爭時，它們都有動機接觸同一批開發者。</p><p>因此一個中立的開源平台可能成為：</p><p>- 開發者入口；</p><p>- 模型分發渠道；</p><p>- 生態競爭的戰場；</p><p>- 不同供應商共同需要的基礎層。</p><p><strong>中立層的脆弱性</strong></p><p>但中立層也會暴露於上游政策風險：</p><p>- API 政策改變；</p><p>- subscription 使用限制；</p><p>- rate limit 調整；</p><p>- 模型供應商自建競品；</p><p>- 法律或商業條款改變。</p><p>所以 bridge business 一直有一個結構性矛盾：</p><p>越連接多個上游系統</p><blockquote>→ 連接價值越高</blockquote><blockquote>→ 也越容易受到上游變化影響</blockquote><h3><strong>OpenCode 的商業化路徑</strong></h3><p>根據訪談整理，OpenCode 的商業化主要有兩個方向。</p><p><strong>1. Hosted inference：OpenCode Zen</strong></p><p>OpenCode Zen 主要解決：</p><p>- API key 配置；</p><p>- rate limit；</p><p>- 模型選擇；</p><p>- 開源模型部署；</p><p>- 推理效能。</p><p>這是一條典型的開源商業化路徑：</p><blockquote>開源客戶端</blockquote><blockquote>→ 開發者採用</blockquote><blockquote>→ hosted convenience</blockquote><blockquote>→ inference revenue</blockquote><p>訪談摘要提到約 US$50M annualised revenue，但這個數字目前仍然屬於創辦人說法，沒有在本輪研究中獲得獨立財務資料驗證。</p><p><strong>2. Enterprise control plane</strong></p><p>當企業有數百甚至上千名工程師使用 coding agent 時，單純讓每個工程師自行配置 API key 已經不可行。</p><p>企業需要統一管理：</p><p>- model providers；</p><p>- permissions；</p><p>- budget；</p><p>- rate limits；</p><p>- usage；</p><p>- governance；</p><p>- security policies。</p><p>因此，另一條路徑是：</p><blockquote>開源工具</blockquote><blockquote>→ 開發者分發</blockquote><blockquote>→ 企業控制層</blockquote><blockquote>→ 權限、審計、預算和治理收入</blockquote><p><strong>對 HK Enterprise Bridge 的啟示</strong></p><p>HK Bridge 不應該做「香港版 Cursor」。</p><p>更值得探索的是：</p><blockquote>香港本地制度 / 企業 workflow gap</blockquote><blockquote>+ 中立 connector layer</blockquote><blockquote>+ 權限和 human approval</blockquote><blockquote>+ verification / audit trail</blockquote><blockquote>+ 行業知識</blockquote><p>真正的產品價值不只是：</p><blockquote>幫企業更快寫 integration。</blockquote><p>而是：</p><p>- 幫企業減少跨部門協調；</p><p>- 幫企業追蹤跨系統狀態；</p><p>- 幫企業處理例外；</p><p>- 幫企業驗證資料；</p><p>- 幫企業保留可審計的執行記錄；</p><p>- 幫企業知道甚麼時候必須交回人手處理。</p><p><strong>Product rot 是 Bridge product 的核心風險</strong></p><p>每接一個客戶，都可能增加：</p><p>- 一個 connector；</p><p>- 一個例外邏輯；</p><p>- 一個特殊權限；</p><p>- 一個 custom workflow；</p><p>- 一條永久 support obligation。</p><p>如果沒有清晰的產品邊界，最後會變成：</p><blockquote>每個客戶都可以要求一點東西，但沒有人知道核心產品究竟是甚麼。</blockquote><p>所以 HK Bridge 需要從第一天開始建立：</p><p>- connector 邊界；</p><p>- workflow template；</p><p>- exception policy；</p><p>- verification standard；</p><p>- human approval model；</p><p>- stop-building criteria。</p><h3><strong>AI 讓判斷力變得更加昂貴</strong></h3><p>AI coding 真正改變的，可能不是工程師是否需要寫程式，而是「寫程式」不再是主要瓶頸。</p><p>當實作變得便宜，真正昂貴的會是：</p><p>- 對問題的理解；</p><p>- 對產品的取捨；</p><p>- 對架構的判斷；</p><p>- 對風險的承擔；</p><p>- 對長期維護的責任。</p><p>因此，AI 時代最有價值的工程師，未必是寫得最快的人。</p><p>而可能是最清楚知道：</p><p>- 甚麼值得做；</p><p>- 甚麼不應該做；</p><p>- 甚麼需要驗證；</p><p>- 甚麼應該交回人手；</p><p>- 甚麼功能應該永遠拒絕的人。</p><blockquote><strong>AI coding 降低了「把東西做出來」的成本，所以「做甚麼、為甚麼做、哪些東西不應該做」會變得更加昂貴。</strong></blockquote><p><strong>參考資料</strong></p><p>- <a href="https://newsletter.pragmaticengineer.com/p/opencode">The Pragmatic Engineer — Building OpenCode with Dax Raad</a></p><p>- <a href="https://newsletter.pragmaticengineer.com/p/opencode">Taeho Kim — Building OpenCode with Dax Raad</a></p><p>- <a href="https://newsletter.pragmaticengineer.com/p/opencode">Epic Product Engineer — Product sense, restraint, and OpenCode</a></p><p>- <a href="https://newsletter.pragmaticengineer.com/p/opencode">iHeart — Product sense, restraint, and OpenCode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d27874ec5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[中立的 Agent 操縱系統 (Neutral Agent OS)]]></title>
            <link>https://medium.com/@jameskong_35184/%E4%B8%AD%E7%AB%8B%E7%9A%84-agent-%E6%93%8D%E7%B8%B1%E7%B3%BB%E7%B5%B1-neutral-agent-os-d491cd5da664?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/d491cd5da664</guid>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Sun, 31 May 2026 13:23:24 GMT</pubDate>
            <atom:updated>2026-05-31T13:24:58.551Z</atom:updated>
            <content:encoded><![CDATA[<p>2026 年 AI 工程學的核心：從「做聰明的 Agent」轉向「管理聰明的 Agent」。</p><h3>四大技術支柱</h3><h3>1. 模型抽象層 (Agnostic Abstraction)</h3><ul><li>動態路由：任務難度自動切換 (Llama-3 vs Claude 4.5)</li><li>提示詞編譯器：高階業務邏輯轉譯，確保跨模型一致性</li></ul><h3>2. 虛擬化執行環境 (Brain &amp; Hands)</h3><ul><li>無狀態大腦：模型只決策，不存狀態</li><li>臨時沙盒：Wasm/Docker 執行後立即銷毀</li></ul><h3>3. 憑證代理 (Credential Proxy)</h3><ul><li>MCP 協議：統一管理工具接入</li><li>憑證金庫：Agent 永不接觸原始 API Key</li></ul><h3>4. 驗證與治理 (Verification Loop)</h3><ul><li>自動化檢查點：高風險操作觸發審計</li><li>觀測平台：即時查看 Token 消耗與記憶體</li></ul><h3>技術架構圖 (Arch Diagram)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*p8HVRRKOO2UksidV2czlFw.png" /><figcaption><strong>中立 Agent 操縱系統 (The Kernel)</strong></figcaption></figure><ol><li>模型路由器 (Routing)</li><li>會話持久化 (Session)</li><li>安全憑證金庫 (Vault)</li><li>資源調度 &amp; 沙盒隔離 (Sandbox)</li><li>驗證迴圈 (Verification Loop)</li></ol><h3>為什麼這是 Startup 的機會？</h3><p>解決企業合規（Compliance）、成本最佳化（Cost Optimization）以及多供應商（Multi-Vendor）協同。建立「管理聰明 Agent 的管家」層，才是 2026 年最具價值的戰略護城河。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d491cd5da664" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[自動補全到 AI 代理人：程式開發的 3 個層級]]></title>
            <link>https://medium.com/@jameskong_35184/%E8%87%AA%E5%8B%95%E8%A3%9C%E5%85%A8%E5%88%B0-ai-%E4%BB%A3%E7%90%86%E4%BA%BA-%E7%A8%8B%E5%BC%8F%E9%96%8B%E7%99%BC%E7%9A%84-3-%E5%80%8B%E5%B1%A4%E7%B4%9A-fb46abdd314a?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb46abdd314a</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[hermes]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Sat, 30 May 2026 04:31:51 GMT</pubDate>
            <atom:updated>2026-05-30T05:23:04.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>從自動補全到 AI 代理人：程式開發的 3 個層級</h3><p>在 AI 輔助開發的領域，我們正經歷從「輔助工具」到「自主代理人」的範式轉移 (Paradigm Shift)。根據 <strong>Baoyu (Jim Liu)</strong> 的 AI 公司架構模型，我們可以將 AI 程式開發劃分為三個關鍵層級。</p><p><a href="https://fishkingsin.github.io/ai-coding-levels.html">https://fishkingsin.github.io/ai-coding-levels.html</a></p><h3>1. Level 1: 自動補全 (Autocomplete / Shadow)</h3><p>這是最普及的層級。AI 像是 IDE 裡的影子，觀察你的輸入並預測下一段代碼。</p><p><strong>代表工具：</strong> GitHub Copilot, Cursor (Tab 模式)。</p><p><strong>特點：</strong> 高頻率、低延遲。</p><p><strong>侷限：</strong> 缺乏對整體專案架構 (Architecture) 的理解，僅能處理局部語法補全。</p><h3>2. Level 2: 對話驅動 (Chat-Driven / Assistant)</h3><p>這是目前大多數開發者的主流用法。人類作為「橋樑」，與 AI 進行多輪對話。</p><p><strong>代表工具：</strong> ChatGPT, Claude.ai, Gemini。</p><p><strong>工作流：</strong></p><ol><li>人類複製錯誤訊息。</li><li>AI 提供修復建議。</li><li>人類手動將代碼貼回專案。</li></ol><p><strong>侷限：</strong> 「人機隔閡」導致效率瓶頸，容易在複製貼上過程中產生上下文斷層。</p><h3>3. Level 3: 代理人工作流 (Agentic Workflow / Autonomous) 🚀</h3><p>這是程式開發的終極形態。AI 不再只是「給建議」，而是擁有操作環境的「權限」。</p><p><strong>代表工具：</strong> <strong>Hermes Agent</strong>, Claude Code, OpenAI Codex。</p><p><strong>核心能力：</strong></p><p><strong>環境感知：</strong> 直接讀取檔案系統與 Git 歷史。</p><p><strong>工具操作：</strong> 進入 Terminal 執行測試、編譯與部署。</p><p><strong>自主驗證：</strong> 遵循 <strong>TDD (測試驅動開發)</strong>，未經測試通過的代碼不予提交。</p><p><strong>實戰案例：</strong> 在本次實驗中，Hermes 接收到「建立圖表」的指令後，自主完成了：</p><ol><li>設計 HTML/CSS 架構。</li><li>克隆 (Clone) GitHub Pages 儲存庫。</li><li>處理 Git 身份配置與身份驗證 (GITHUB_TOKEN)。</li><li>成功推播 (Push) 至遠端伺服器。</li></ol><h3>🚀 結論：邁向 AI 共創時代</h3><p>從 Level 2 升級到 Level 3，關鍵在於<strong>信任與權限</strong>。當我們建立起完善的 SOP 與自動化測試網後，AI 代理人將成為「01 號員工」，處理瑣碎的部署與除錯，讓人類專注於更高層次的產品設計與決策。</p><ul><li><a href="https://fishkingsin.github.io/ai-coding-levels.html">查看視覺化圖表</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb46abdd314a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Jetpack Compose, MVVM, and Kotlin Flow for Reactive Android Development]]></title>
            <link>https://medium.com/@jameskong_35184/leveraging-jetpack-compose-mvvm-and-kotlin-flow-for-reactive-android-development-0c633bc9a5a8?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c633bc9a5a8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 07:09:03 GMT</pubDate>
            <atom:updated>2024-12-23T07:09:03.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern Android app development has taken a massive leap forward with the introduction of Jetpack Compose, Kotlin Flow, and the MVVM architecture. Together, they provide a clean, reactive approach to building highly dynamic and efficient apps. This article will explore how to build reactive Android applications by combining these technologies, focusing on best practices, clean architecture, and real-world examples.</p><h3>Why Jetpack Compose, MVVM, and Kotlin Flow?</h3><p>The combination of <strong>Jetpack Compose</strong>, <strong>MVVM</strong>, and <strong>Kotlin Flow</strong> simplifies UI development, promotes reactive programming, and makes code more maintainable. Here’s what each of these technologies brings to the table:</p><ol><li><strong>Jetpack Compose</strong>: A modern, declarative UI toolkit that simplifies UI creation by enabling developers to describe how the UI should look and behave.</li><li><strong>MVVM (Model-View-ViewModel)</strong>: A design pattern that separates UI logic from business logic, improving testability and maintainability.</li><li><strong>Kotlin Flow</strong>: A reactive programming library that supports asynchronous data streams, simplifying data handling and state management.</li></ol><p>Together, these tools allow developers to build reactive UIs where the View dynamically updates in response to changes in the underlying data streams.</p><h3>Case Study: Building a Reactive App with Jetpack Compose, MVVM, and Kotlin Flow</h3><p>Let’s explore how to use Jetpack Compose and Kotlin Flow in an MVVM architecture to create a clean, reactive app. For this case study, we’ll use a simple example of fetching and displaying a list of articles, filtered based on user input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*hAug2K7Q5NPKeuHzs5zO1Q.gif" /></figure><h3>Core Architecture</h3><p>Here’s a quick overview of how the architecture is structured:</p><ol><li><strong>Model (Repository)</strong>: Responsible for fetching raw data from the API or database.</li><li><strong>ViewModel</strong>: Acts as the bridge between the Model and the View. It processes raw data into a UI-ready format using Kotlin Flow.</li><li><strong>View (Jetpack Compose)</strong>: Observes data from the ViewModel and updates the UI reactively.</li></ol><h3>Example Code</h3><p>Here’s how you can implement the core architecture:</p><h4>Step 1: Data Model</h4><p>The Article class represents the raw data structure fetched from the backend.</p><pre>data class Article(<br>    val id: Int,<br>    val title: String,<br>    val author: String<br>)</pre><h4>Step 2: Repository Layer</h4><p>The ArticleRepository fetches articles from the API and simulates a delay to mimic network latency.</p><pre>class ArticleRepository {<br><br>    private val articles = listOf(<br>        Article(1, &quot;Kotlin Flow and MVVM&quot;, &quot;Author A&quot;),<br>        Article(2, &quot;Jetpack Compose Basics&quot;, &quot;Author B&quot;),<br>        Article(3, &quot;Reactive Programming in Android&quot;, &quot;Author C&quot;)<br>    )<br><br>    fun fetchArticles(): Flow&lt;List&lt;Article&gt;&gt; {<br>        return flow {<br>            delay(1000) // Simulate network delay<br>            emit(articles)<br>        }<br>    }<br>}</pre><h4>Step 3: ViewModel with Reactive Programming</h4><p>The MainViewModel processes user input and data streams using Kotlin Flow.</p><pre><br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.viewModelScope<br>import kotlinx.coroutines.CoroutineScope<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.FlowPreview<br>import kotlinx.coroutines.Job<br>import kotlinx.coroutines.SupervisorJob<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.StateFlow<br>import kotlinx.coroutines.flow.catch<br>import kotlinx.coroutines.flow.combine<br>import kotlinx.coroutines.flow.debounce<br>import kotlinx.coroutines.launch<br><br>@OptIn(FlowPreview::class)<br>class MainViewModel : ViewModel() {<br>    private val repository = ArticleRepository()<br><br>    // State for search input<br>    private val _searchText = MutableStateFlow(&quot;&quot;)<br>    val searchText: StateFlow&lt;String&gt; = _searchText<br><br>    // State for filtered articles<br>    private val _articles = MutableStateFlow&lt;List&lt;Article&gt;&gt;(emptyList())<br>    val articles: StateFlow&lt;List&lt;Article&gt;&gt; = _articles<br><br>    private val _error = MutableStateFlow&lt;String?&gt;(null)<br>    val error: StateFlow&lt;String?&gt; = _error<br><br>    private val job = SupervisorJob()<br>    private val scope = CoroutineScope(Dispatchers.IO + job)<br><br>    init {<br>        // Combine search text and articles to filter results reactively<br>        scope.launch {<br>            _searchText<br>                .debounce(300) // Reduce frequent updates<br>                .combine(repository.fetchArticles()) { searchText, articles -&gt;<br>                    articles.filter { article -&gt;<br>                        searchText.isEmpty() || article.title.contains(searchText, ignoreCase = true)<br>                    }<br>                }<br>                .catch { e -&gt;<br>                    _error.emit(&quot;Error fetching articles: ${e.message}&quot;)<br>                }<br>                .collect {<br>                    _articles.emit(it)<br>                }<br>        }<br>    }<br><br>    fun fetchArticles(): Job = viewModelScope.launch {<br>        repository.fetchArticles().collect {<br>            _articles.emit(it)<br>        }<br><br>    }<br><br>    fun onSearchTextChanged(newText: String) {<br>        _searchText.value = newText<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        job.cancel()<br>    }<br>}</pre><h4>Step 4: Jetpack Compose UI</h4><p>The ContentView observes the state from the ViewModel and updates the UI dynamically.</p><pre><br>import androidx.compose.foundation.layout.*<br>import androidx.compose.foundation.lazy.LazyColumn<br>import androidx.compose.foundation.lazy.items<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.Text<br>import androidx.compose.material3.TextField<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.LaunchedEffect<br>import androidx.compose.runtime.collectAsState<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.unit.dp<br>import androidx.compose.ui.Modifier<br>import androidx.lifecycle.viewmodel.compose.viewModel<br>import androidx.compose.runtime.getValue<br>import androidx.compose.ui.tooling.preview.Preview<br><br>@Composable<br>fun ContentView(modifier: Modifier, viewModel: MainViewModel = viewModel() ) {<br>    val articles: List&lt;Article&gt; by viewModel.articles.collectAsState()<br>    val searchText by viewModel.searchText.collectAsState()<br>    val error by viewModel.error.collectAsState()<br><br>    LaunchedEffect(viewModel, 0) {<br>        viewModel.fetchArticles()<br>    }<br><br>    Column(modifier = modifier.padding(16.dp)) {<br>        TextField(<br>            value = searchText,<br>            onValueChange = { viewModel.onSearchTextChanged(it) },<br>            modifier = Modifier.fillMaxWidth(),<br>            label = { Text(&quot;Search articles...&quot;, modifier = Modifier) }<br>        )<br><br>        Spacer(modifier = Modifier.height(16.dp))<br><br>        if (!error.isNullOrEmpty()) {<br>            Text(&quot;Error: $error&quot;, color = Color.Red)<br>        }<br><br>        LazyColumn {<br>            items(articles) { article -&gt;<br>                Column(modifier = Modifier.padding(8.dp)) {<br>                    Text(article.title, style = MaterialTheme.typography.bodyLarge)<br>                    Text(&quot;By ${article.author}&quot;, style = MaterialTheme.typography.bodySmall)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Preview(showBackground = true, showSystemUi = true)<br>@Composable<br>fun ContentViewPreview() {<br>    MaterialTheme {<br>        ContentView(Modifier.fillMaxSize())<br>    }<br>}</pre><h3>Reactive Programming in Action</h3><p>The combination of combine, debounce, and collect in the ViewModel ensures that:</p><ul><li><strong>Dynamic Updates</strong>: The UI reacts instantly to changes in the search input or fetched data.</li><li><strong>Efficient Processing</strong>: The debounce operator prevents excessive updates when the user types quickly.</li><li><strong>Error Handling</strong>: Errors are caught and displayed to the user, ensuring a smooth experience.</li></ul><h3>Benefits of This Architecture</h3><ol><li><strong>Separation of Concerns</strong>: The MVVM pattern keeps UI logic, business logic, and data access layers independent.</li><li><strong>Reactive Updates</strong>: Changes in data or user input automatically reflect in the UI, reducing manual state management.</li><li><strong>Simplified UI Code</strong>: Jetpack Compose eliminates the boilerplate code traditionally associated with Android UI development.</li><li><strong>Scalable Design</strong>: Kotlin Flow ensures efficient handling of asynchronous streams, making the app scalable.</li></ol><h3>Best Practices</h3><ol><li><strong>Use </strong><strong>StateFlow for State Management</strong>: It’s lifecycle-aware and ensures consistent state updates across the app.</li><li><strong>Combine Operators for Reactive Logic</strong>: Operators like combine, debounce, and catch simplify handling data streams.</li><li><strong>Error Handling</strong>: Always provide user-friendly error messages to enhance the user experience.</li><li><strong>Testing</strong>: Write unit tests for your ViewModel to verify the data flow logic.</li></ol><h3>Conclusion</h3><p>Jetpack Compose, MVVM, and Kotlin Flow together create a powerful combination for building reactive Android apps. This architecture simplifies UI development, enhances app responsiveness, and ensures a clean, scalable codebase. By leveraging these tools, you can deliver high-quality applications with minimal complexity.</p><p>Ready to dive deeper? Check out the full implementation in the <a href="https://github.com/fishkingsin/FlowWithMVVMExample">GitHub Repository</a> and start building reactive Android apps today! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c633bc9a5a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Case Study: Reactive Programming with MVVM, SwiftUI, and Combine]]></title>
            <link>https://medium.com/@jameskong_35184/case-study-reactive-programming-with-mvvm-swiftui-and-combine-1f3d1c1907a2?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f3d1c1907a2</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 06:28:40 GMT</pubDate>
            <atom:updated>2024-12-23T10:17:32.166Z</atom:updated>
            <content:encoded><![CDATA[<h4>Below, we demonstrate how data streams from the backend are processed and transformed into a UI-ready format using Combine.</h4><h3>Data Flow Architecture</h3><p>The ViewModel acts as the bridge between the backend (Model) and the user interface (View). Combine operators are used to manage and manipulate data streams at this layer. Here’s how it works:</p><ol><li><strong>Input</strong>: User actions or backend events trigger updates.</li><li><strong>Processing</strong>: Combine operators transform raw data into UI-ready models.</li><li><strong>Output</strong>: The processed data is dynamically reflected in the UI.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*vsgMwSiVJVwFocvlgtLsyA.gif" /></figure><h3>Source Code Overview</h3><p>Let’s consider the MainViewModel.swift implementation, where Combine is used to handle the data flow:</p><pre>import SwiftUI<br>import Combine<br><br>struct Article: Identifiable, Hashable, Equatable {<br>    var id: UUID = UUID()<br>    var title: String<br>    var subtitle: String<br>}<br><br>class MainViewModel: ObservableObject {<br>    @Published var searchText: String = &quot;&quot;<br>    @Published var articles: [Article] = []<br>    <br>    private var serahPublisher: AnyPublisher&lt;[Article], Never&gt; {<br>        $searchText<br>            .combineLatest(fetchArticlesPublisher())<br>            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)<br>            .map { searchText, articles in<br>                // Filter articles based on the search text<br>                articles.filter { article in<br>                    searchText.isEmpty || article.title.contains(searchText)<br>                }<br>            }<br>            .map { filteredArticles in<br>                // Transform filtered articles into DisplayArticleViewModels<br>                filteredArticles.map { article in<br>                    Article(<br>                        title: article.title,<br>                        subtitle: &quot;By \(article.subtitle)&quot;<br>                    )<br>                }<br>            }.eraseToAnyPublisher()<br>    }<br>    var cancellables: Set&lt;AnyCancellable&gt; = []<br>    func fetchArticles() {<br>        articles = [<br>            Article(title: &quot;SwiftUI&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>            Article(title: &quot;Combine&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>            Article(title: &quot;SwiftUI&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>            Article(title: &quot;Combine&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>        ]<br>        <br>    }<br>    <br>    func fetchArticlesPublisher() -&gt; AnyPublisher&lt;[Article], Never&gt; {<br>        Just([<br>            Article(title: &quot;SwiftUI&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>            Article(title: &quot;Combine&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>            Article(title: &quot;SwiftUI&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>            Article(title: &quot;Combine&quot;, subtitle: &quot;A SwiftUI framework&quot;),<br>        ])<br>        .delay(for: .milliseconds(100), scheduler: RunLoop.main)<br>        .eraseToAnyPublisher()<br>    }<br>    <br>    init() {<br>        // subscribe to publiser and update articles<br>        searchArticles()<br>    }<br>    <br>    private func searchArticles() {<br>        serahPublisher<br>            .receive(on: DispatchQueue.main) // Ensure UI updates happen on the main thread<br>            .sink(receiveCompletion: { completion in<br>                // Handle errors in the pipeline<br>                if case let .failure(error) = completion {<br>                    print(&quot;Error: \(error.localizedDescription)&quot;)<br>                }<br>            }, receiveValue: { [weak self] displayArticles in<br>                // Update the published property for UI binding<br>                self?.articles = displayArticles<br>            })<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3>Key Combine Operators in Action</h3><p>Here’s a breakdown of the Combine operators used in the example:</p><ol><li><strong>combineLatest</strong>: Combines the user’s search input ($searchText) with the fetched articles from the backend (apiService.fetchArticles()), ensuring that the UI reacts to changes in either stream.</li><li><strong>debounce</strong>: Reduces redundant operations by waiting for the user to finish typing before filtering the articles.</li><li><strong>map</strong>: Processes the data stream in two stages: 1. Filters the articles based on the search text. 2. Converts the filtered articles into a UI-friendly format (DisplayArticleViewModel).</li><li><strong>receive(on:)</strong>: Ensures all UI updates happen on the main thread, preventing threading issues.</li><li><strong>sink</strong>: Subscribes to the processed data stream and updates the UI state.</li></ol><h3>ViewModel and SwiftUI Integration</h3><p>The ViewModel exposes the transformed data to the SwiftUI View through a @Published property, enabling real-time UI updates. Here’s how the View is implemented:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @ObservedObject private var viewModel = MainViewModel()<br>    var body: some View {<br>        VStack {<br>            TextField(&quot;Search...&quot;, text: $viewModel.searchText)<br>                .textFieldStyle(RoundedBorderTextFieldStyle())<br>                .padding()<br>            List(viewModel.articles) { article in<br>                VStack(alignment: .leading) {<br>                    Text(article.title)<br>                        .font(.headline)<br>                    Text(article.subtitle)<br>                        .font(.subheadline)<br>                }<br>            }<br>        }<br>        .onAppear {<br>            viewModel.fetchArticles()<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><h3>Best Practices for Mobile Clean Architecture</h3><ol><li><strong>Embrace MVVM</strong>: Use the ViewModel to handle all business logic and data processing, keeping the View focused on rendering the UI.</li><li><strong>Leverage Reactive Programming</strong>: Combine operators like map, filter, and combineLatest make it easy to process and transform data streams. Use debounce and throttle to optimize user input handling.</li><li><strong>Swift Combine for Asynchronous Tasks</strong>: Simplify asynchronous workflows like API calls and user input handling with Combine. Ensure memory safety using store(in:) to manage subscriptions.</li><li><strong>SwiftUI for Declarative UI</strong>: Bind UI components directly to @Published properties in the ViewModel for real-time updates. Keep Views lightweight and focus on layout and styling.</li></ol><h3>Enhancements in Reactive Programming</h3><p>The following enhancements can improve your implementation further:</p><ul><li><strong>Error Handling</strong>: Implement user-friendly error messages to handle issues like network failures.</li><li><strong>Testability</strong>: Write unit tests for the Combine pipelines to ensure data transformations work as expected.</li><li><strong>Modularization</strong>: Break down complex pipelines into smaller reusable functions for better readability and maintainability.</li></ul><h3>Conclusion</h3><p>By integrating <strong>SwiftUI</strong>, <strong>MVVM</strong>, and <strong>Combine</strong>, you can create scalable, maintainable, and reactive mobile applications. The combination of declarative UI and reactive programming simplifies state management and ensures your app responds dynamically to user interactions and data changes. With the best practices outlined in this article, you’ll be well-equipped to design clean and efficient architectures for your iOS apps.</p><p>For a full implementation, check out the <a href="https://github.com/fishkingsin/CombineWithMVVMExample">repository</a> and start building your next mobile app with these powerful tools! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f3d1c1907a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migration Guide: From android.webkit.WebView]]></title>
            <link>https://medium.com/@jameskong_35184/migration-guide-from-android-webkit-webview-3fc1232d6f57?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fc1232d6f57</guid>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 09:54:41 GMT</pubDate>
            <atom:updated>2024-09-30T09:54:41.443Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migration Guide: From android.webkit.WebView + Android View to androidx.webkit:webkit + Jetpack Compose</h3><p>This migration guide helps Android developers transition from the legacy android.webkit.WebView embedded within Android Views to androidx.webkit:webkit using <strong>Jetpack Compose</strong>, the modern declarative UI framework for Android development. androidx.webkit provides enhanced features such as safe browsing, JavaScript interface security, and compatibility with newer APIs, while <strong>Jetpack Compose</strong> allows you to build UIs declaratively.</p><h3>Prerequisites</h3><ul><li><strong>Jetpack Compose</strong> version 1.0.0 or later.</li><li><strong>Android Studio</strong> with Compose and Kotlin support.</li><li><strong>androidx.webkit</strong>version 1.4.0 or later.</li></ul><h3>1. Why Migrate?</h3><p>Migrating from android.webkit.WebView to androidx.webkit:webkit with <strong>Jetpack Compose</strong> allows you to:</p><ul><li>Use modern, reactive, and declarative UI paradigms with Jetpack Compose.</li><li>Leverage advanced web features with androidx.webkit.</li><li>Enhance security and flexibility with new APIs available in androidx.webkit.</li><li>Simplify your UI code with Jetpack Compose, which replaces the traditional View-based XML approach.</li></ul><h3>2. Jetpack Compose Overview</h3><p>Before migrating, it’s important to understand the differences between the traditional View-based system and Jetpack Compose. Jetpack Compose allows developers to describe the UI in a declarative manner using Kotlin.</p><p>Traditional View-based code:</p><pre>&lt;WebView<br>    android:id=&quot;@+id/myWebView&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;/&gt;</pre><p>Jetpack Compose uses composables, which are functions that define UI components:</p><pre>WebView(url = &quot;https://www.example.com&quot;)</pre><h3>3. Migrate Dependencies</h3><p>Make sure you add the necessary dependencies for androidx.webkit and Jetpack Compose in your build.gradle:</p><pre>dependencies {<br>    // Jetpack Compose dependencies<br>    implementation &quot;androidx.compose.ui:ui:1.4.0&quot;<br>    implementation &quot;androidx.compose.material:material:1.4.0&quot;<br>    implementation &quot;androidx.activity:activity-compose:1.7.0&quot;<br><br>    // WebKit dependency<br>    implementation &quot;androidx.webkit:webkit:1.7.0&quot;<br>}</pre><p>Enable Jetpack Compose in your build.gradle:</p><pre>android {<br>    buildFeatures {<br>        compose true<br>    }<br>    composeOptions {<br>        kotlinCompilerExtensionVersion &#39;1.4.0&#39;<br>    }<br>}</pre><h3>4. Migrate WebView from View-based to Jetpack Compose</h3><h4>4.1 Current android.webkit.WebView in XML with View-based Code</h4><p>Traditional View-based WebView implementation:</p><p><strong>XML Layout (</strong><strong>activity_main.xml):</strong></p><pre>&lt;WebView<br>    android:id=&quot;@+id/myWebView&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot; /&gt;</pre><p>Activity (MainActivity.java or MainActivity.kt):</p><pre>class MainActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        val webView: WebView = findViewById(R.id.myWebView)<br>        webView.webViewClient = WebViewClient()  // To keep the web page within the app<br>        webView.loadUrl(&quot;https://www.example.com&quot;)<br>    }<br>}</pre><h4>4.2 Migrating to androidx.webkit:webkit in Jetpack Compose</h4><p>Since Jetpack Compose doesn’t have a direct WebView composable, we use AndroidView to integrate WebView. The AndroidView function allows embedding traditional views in Compose.</p><pre>import android.os.Bundle<br>import android.webkit.WebView<br>import android.webkit.WebViewClient<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.viewinterop.AndroidView<br>import androidx.webkit.WebSettingsCompat<br>import androidx.webkit.WebViewFeature<br><br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MyWebViewScreen(url = &quot;https://www.example.com&quot;)<br>        }<br>    }<br>}<br><br>@Composable<br>fun MyWebViewScreen(url: String) {<br>    AndroidView(<br>        modifier = Modifier.fillMaxSize(),<br>        factory = { context -&gt;<br>            WebView(context).apply {<br>                webViewClient = WebViewClient()  // Keep web content within the app<br><br>                settings.javaScriptEnabled = true  // Enable JavaScript<br>                loadUrl(url)<br><br>                // Using androidx.webkit for Dark Mode Support (Optional)<br>                if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {<br>                    WebSettingsCompat.setForceDark(settings, WebSettingsCompat.FORCE_DARK_ON)<br>                }<br>            }<br>        },<br>        update = { webView -&gt;<br>            webView.loadUrl(url)<br>        }<br>    )<br>}</pre><h4>Key Elements:</h4><ul><li><strong>AndroidView</strong>: This composable is used to bridge Compose with traditional Android Views like WebView.</li><li><strong>WebViewClient</strong>: Ensures that links are opened within the WebView instead of an external browser.</li><li><strong>WebSettingsCompat.setForceDark</strong>: Part of the androidx.webkit library to enable dark mode (optional).</li></ul><h4>4.3 Handling Navigation Control in Compose</h4><p>If you need to provide navigation control (e.g., back and forward buttons), you can expose the navigation control inside your Compose UI.</p><pre>@Composable<br>fun MyWebViewWithControls(url: String) {<br>    var webView: WebView? = null<br><br>    Column {<br>        AndroidView(<br>            modifier = Modifier.weight(1f),  // WebView takes up most of the screen<br>            factory = { context -&gt;<br>                WebView(context).apply {<br>                    webViewClient = WebViewClient()<br>                    settings.javaScriptEnabled = true<br>                    loadUrl(url)<br><br>                    webView = this  // Save a reference to the WebView<br>                }<br>            }<br>        )<br>        // Buttons for navigation<br>        Row(<br>            modifier = Modifier.padding(16.dp),<br>            horizontalArrangement = Arrangement.SpaceEvenly<br>        ) {<br>            Button(onClick = { webView?.goBack() }, enabled = webView?.canGoBack() == true) {<br>                Text(&quot;Back&quot;)<br>            }<br>            Button(onClick = { webView?.goForward() }, enabled = webView?.canGoForward() == true) {<br>                Text(&quot;Forward&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>5. Handling JavaScript in WKWebView</h3><p>If your app needs JavaScript interaction (like adding a JavaScript interface), you can continue using the WebView&#39;s existing APIs with androidx.webkit:</p><pre>webView.addJavascriptInterface(object {<br>    @JavascriptInterface<br>    fun showToast(message: String) {<br>        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()<br>    }<br>}, &quot;Android&quot;)</pre><h4>Handling Permissions in Jetpack Compose</h4><p>Ensure that your AndroidManifest.xml contains the following permissions for using WebView:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><h3>6. Additional Features in androidx.webkit</h3><p>With androidx.webkit, you get access to new features like:</p><ul><li><strong>Safe Browsing</strong>: Protects users from malicious URLs. To enable:</li></ul><pre>if (WebViewFeature.isFeatureSupported(WebViewFeature.SAFE_BROWSING_ENABLE)) {<br>    WebSettingsCompat.setSafeBrowsingEnabled(settings, true)<br>}</pre><ul><li><strong>Debugging WebView</strong>: You can enable web debugging using:</li></ul><pre>WebView.setWebContentsDebuggingEnabled(true)</pre><h3>7. Conclusion</h3><p>By migrating to androidx.webkit:webkit with <strong>Jetpack Compose</strong>, you can modernize your app’s architecture, enhance UI flexibility, and leverage more powerful WebView APIs. Jetpack Compose simplifies UI development, making it easier to maintain and expand the web content in your Android app.</p><p><strong>Next Steps:</strong></p><ul><li>Replace all instances of SFSafariViewController with WKWebView where necessary.</li><li>Test your web views thoroughly for all interactions, navigation, and JavaScript handling.</li><li>Ensure backward compatibility by testing on devices running older Android versions.</li></ul><p>This migration to androidx.webkit:webkit in combination with <strong>Jetpack Compose</strong> will help you build a more modern and future-proof application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fc1232d6f57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migration Guide: From SFSafariViewController to WKWebView in SwiftUI]]></title>
            <link>https://medium.com/@jameskong_35184/migration-guide-from-sfsafariviewcontroller-to-wkwebview-in-swiftui-221013107556?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/221013107556</guid>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 09:49:33 GMT</pubDate>
            <atom:updated>2024-09-30T09:49:33.473Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide, you’ll learn how to transition from using SFSafariViewController to WKWebView in a <strong>SwiftUI</strong> application. While SFSafariViewController is an easy-to-use web browser view provided by Apple, WKWebView offers far more control over web content rendering within your app, which is highly desirable in custom applications. Here&#39;s how you can achieve this in SwiftUI.</p><h3>1. Understand the Key Differences</h3><p>Before we dive into the implementation, let’s reiterate the key differences:</p><p>FeatureSFSafariViewControllerWKWebViewControllerSystem-provided web view controllerCustomizable web view in your appUser InterfaceLimited customization, looks like SafariFull control over the UICookies and Data StorageShared with SafariIsolated from SafariJavaScript ControlLimitedFull control over JavaScriptNavigation ControlsProvided by defaultNeed to implement manuallySecurityHigh security due to isolationMore responsibility on the developer</p><p>WKWebView is flexible and powerful, but it requires additional effort to implement navigation and UI controls when using SwiftUI.</p><h3>2. Setting Up WKWebView in SwiftUI</h3><p>SwiftUI does not provide a direct WKWebView element. Instead, we’ll use UIViewRepresentable to bridge the gap between UIKit (where WKWebView resides) and SwiftUI. This enables us to display a WKWebView inside a SwiftUI view.</p><h3>2.1 Creating a WebView Struct</h3><p>We will create a WebView struct that will represent the WKWebView in SwiftUI.</p><pre>import SwiftUI<br>import WebKit<br>struct WebView: UIViewRepresentable {<br>    let url: URL<br>    <br>    func makeUIView(context: Context) -&gt; WKWebView {<br>        let webView = WKWebView()<br>        webView.navigationDelegate = context.coordinator<br>        let request = URLRequest(url: url)<br>        webView.load(request)<br>        return webView<br>    }<br>    <br>    func updateUIView(_ webView: WKWebView, context: Context) {<br>        // Handle any view updates here<br>    }<br>    <br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(self)<br>    }<br>    <br>    class Coordinator: NSObject, WKNavigationDelegate {<br>        var parent: WebView<br>        <br>        init(_ parent: WebView) {<br>            self.parent = parent<br>        }<br>        <br>        // Navigation handling<br>        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {<br>            // Start loading<br>        }<br>        <br>        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {<br>            // Finished loading<br>        }<br>        <br>        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {<br>            // Handle errors<br>        }<br>    }<br>}</pre><h3>2.2 Using WebView in Your SwiftUI View</h3><p>Now that we have the WebView struct set up, you can use it inside any SwiftUI view.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        WebView(url: URL(string: &quot;https://www.example.com&quot;)!)<br>            .edgesIgnoringSafeArea(.all)  // To make the WebView take up the entire screen<br>    }<br>}</pre><h3>2.3 Adding Navigation Controls</h3><p>SFSafariViewController provides automatic navigation controls like &quot;back&quot; and &quot;forward,&quot; but WKWebView requires that you implement these yourself. To add these controls, you need to expose methods for navigation in the WebView and create corresponding buttons in the SwiftUI view.</p><h4>Modify WebView for Navigation:</h4><p>We will add functions for goBack and goForward:</p><pre>struct WebView: UIViewRepresentable {<br>    let url: URL<br>    let webView = WKWebView()<br>    <br>    func makeUIView(context: Context) -&gt; WKWebView {<br>        webView.navigationDelegate = context.coordinator<br>        let request = URLRequest(url: url)<br>        webView.load(request)<br>        return webView<br>    }<br>    <br>    func updateUIView(_ uiView: WKWebView, context: Context) {<br>        // Update the web view when SwiftUI state changes<br>    }<br>    <br>    func goBack() {<br>        if webView.canGoBack {<br>            webView.goBack()<br>        }<br>    }<br>    <br>    func goForward() {<br>        if webView.canGoForward {<br>            webView.goForward()<br>        }<br>    }<br><br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(self)<br>    }<br><br>    class Coordinator: NSObject, WKNavigationDelegate {<br>        var parent: WebView<br>        <br>        init(_ parent: WebView) {<br>            self.parent = parent<br>        }<br><br>        // Navigation Delegate Methods<br>        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {<br>            // Called when navigation starts<br>        }<br>        <br>        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {<br>            // Called when navigation finishes<br>        }<br>        <br>        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {<br>            // Handle any errors during navigation<br>        }<br>    }<br>}</pre><p>Create Buttons in SwiftUI View:</p><p>You can now create buttons in SwiftUI to control the navigation:</p><pre>struct ContentView: View {<br>    @State private var webView = WebView(url: URL(string: &quot;https://www.example.com&quot;)!)<br><br>    var body: some View {<br>        VStack {<br>            HStack {<br>                Button(action: {<br>                    webView.goBack()<br>                }) {<br>                    Text(&quot;Back&quot;)<br>                }<br>                Button(action: {<br>                    webView.goForward()<br>                }) {<br>                    Text(&quot;Forward&quot;)<br>                }<br>            }<br>            .padding()<br>            <br>            webView<br>                .edgesIgnoringSafeArea(.all)<br>        }<br>    }<br>}</pre><h3>2.4 Error Handling in WebView</h3><p>To ensure that your app handles errors gracefully (e.g., if a page fails to load), modify the Coordinator class to handle loading errors:</p><pre>func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {<br>    // Handle load failure here (e.g., display an alert)<br>    print(&quot;Failed to load: \(error.localizedDescription)&quot;)<br>}</pre><h3>3. Adding JavaScript Interaction (Optional)</h3><p>If you need to interact with the webpage’s JavaScript, you can use WKUserContentController in WKWebView. For example:</p><pre>let contentController = WKUserContentController()<br>let userScript = WKUserScript(source: &quot;document.body.style.backgroundColor = &#39;lightblue&#39;;&quot;, injectionTime: .atDocumentEnd, forMainFrameOnly: true)<br>contentController.addUserScript(userScript)<br><br>webView.configuration.userContentController = contentController</pre><p>4. Conclusion</p><p>By using WKWebView within SwiftUI, you can now have full control over web content inside your application. Unlike SFSafariViewController, which is simpler but less customizable, WKWebView gives you complete flexibility in terms of UI, navigation control, error handling, and JavaScript interaction.</p><h3>Next Steps:</h3><ul><li>Test your new WKWebView integration thoroughly, ensuring proper navigation, error handling, and performance.</li><li>If you need more advanced features (such as cookie management, caching, etc.), make sure to add the necessary configurations to WKWebView.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221013107556" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Successfully Integrating UnionPay: A Comprehensive Testing Strategy That Ensures Stability…]]></title>
            <link>https://medium.com/@jameskong_35184/successfully-integrating-unionpay-a-comprehensive-testing-strategy-that-ensures-stability-c1470182088f?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1470182088f</guid>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 14:20:00 GMT</pubDate>
            <atom:updated>2024-08-10T14:20:00.642Z</atom:updated>
            <content:encoded><![CDATA[<h2>🚀 Successfully Integrating UnionPay: A Comprehensive Testing Strategy That Ensures Stability, Quality, and Speed to Market 🚀</h2><p>Thrilled to share insights from our latest UnionPay integration project, where we employed a multi-faceted testing strategy to deliver a robust, high-quality product at lightning speed. Here’s how we did it:</p><p>1️⃣ Test-Driven Development (TDD):</p><p>We began with TDD, writing unit tests before any production code. This approach ensured that each component was designed with clear expectations and met our high standards from the start. TDD helped us catch issues early and build a solid foundation for the integration.</p><p>2️⃣ WebIntegrationTests:</p><p>To validate our services in a real-world context, we used WebIntegrationTests. These tests allowed us to simulate HTTP requests and verify that our API endpoints interacted correctly with other services. This rigorous testing of interactions ensured that our UnionPay integration would function smoothly in various scenarios.</p><p>3️⃣ Business Process API (BPAPI) Tests:</p><p>Given the complexity of financial transactions, BPAPI tests were essential to validate end-to-end business processes. These tests covered all possible transaction permutations, providing confidence that our integration would perform flawlessly in a live environment. Automating these tests reduced the risk of human error and significantly accelerated our testing phase.</p><p>4️⃣ E2E Manual Testing:</p><p>Despite the high cost, we conducted End-to-End (E2E) manual testing to validate the entire workflow from the user’s perspective. Manual testing is resource-intensive, requiring both time and skilled testers, but it is necessary to capture nuanced issues that automation might miss. This step was crucial for verifying that all systems and integrations worked together seamlessly and that the user experience met our high standards.</p><p>🚀 The Result?</p><p>By combining TDD, WebIntegrationTests, BPAPI tests, and E2E manual testing, we achieved:</p><p>•	High Product Stability: Every aspect of the integration was rigorously tested, resulting in a stable and reliable product.</p><p>•	Top-notch Quality: The layered testing approach ensured that both individual components and the entire system met our quality benchmarks.</p><p>•	Rapid Time to Market: Automation and comprehensive testing enabled us to move quickly through the development and release phases, delivering the integration on schedule.</p><p>While manual testing was costly, it was an indispensable part of our strategy, ensuring that the final product met the expectations of our users and stakeholders. If you’re tackling similar complex integrations, I highly recommend adopting a multi-layered testing approach to ensure both quality and speed.</p><p>Would love to hear how others are leveraging similar testing strategies in their projects!</p><p>#UnionPay #Integration #TestingStrategy #TDD #WebIntegrationTests #BPAPITests #E2ETesting #QualityAssurance #Fintech #SoftwareDevelopment #Teamwork</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1470182088f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Embracing TDD in Spring Boot Microservices: The Good, the Bad, and the Lessons Learned ]]></title>
            <link>https://medium.com/@jameskong_35184/embracing-tdd-in-spring-boot-microservices-the-good-the-bad-and-the-lessons-learned-2c388302d137?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c388302d137</guid>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 06:06:08 GMT</pubDate>
            <atom:updated>2024-08-10T06:06:08.838Z</atom:updated>
            <content:encoded><![CDATA[<p>Leading a team of backend engineers, we’ve adopted Test-Driven Development (TDD) across our Spring Boot-based microservices. This approach has brought significant benefits, but it’s also highlighted a few challenges worth sharing.</p><p>💼 <strong>Advantages of TDD in Microservices</strong>:</p><p>1.	<strong>High Code Quality</strong>: Writing tests first forces us to think through the design and implementation before writing the actual code. This results in cleaner, more reliable code, reducing the likelihood of bugs slipping into production.</p><p>2.	<strong>Faster Debugging</strong>: With comprehensive unit tests and WebIntegrationTests in place, identifying and fixing bugs becomes quicker. We can pinpoint issues more accurately, saving time and effort in debugging.</p><p>3.	<strong>Confidence in Refactoring</strong>: TDD provides a safety net when refactoring code. With an extensive suite of tests, we can confidently make changes, knowing that our tests will catch any unintended side effects.</p><p>4.	<strong>Documentation</strong>: Tests serve as living documentation for the codebase. They provide a clear understanding of how different components interact, making it easier for new team members to get up to speed.</p><p>🛑 Drawbacks and Challenges:</p><p>1.	<strong>Initial Time Investment</strong>: TDD requires writing tests before the actual code, which can slow down development initially. However, this time investment often pays off in the long run by reducing the time spent on debugging and maintenance.</p><p>2.	<strong>Complex Test Management</strong>: As the project grows, managing a large number of tests can become challenging. Tests need to be carefully maintained and updated to reflect changes in the codebase, which can be time-consuming.</p><p>3.	<strong>Overemphasis on Testing</strong>: It’s possible to become too focused on achieving 80% test coverage, potentially leading to an over-engineered test suite. It’s crucial to balance the quality and quantity of tests to ensure they add real value.</p><p>4.	<strong>Difficulty in Testing Complex Scenarios</strong>: Some scenarios, especially those involving external dependencies or complex interactions between microservices, can be tricky to test in isolation. WebIntegrationTests can help, but they require careful setup and maintenance.</p><p>5.	<strong>Incorrect Hypotheses and User Acceptance Criticism</strong>: TDD is built on the premise that we can accurately predict how our code will behave in production. However, if our initial assumptions are incorrect, our tests might give us a false sense of security. Additionally, relying too heavily on TDD might lead us to overrate its effectiveness, potentially overlooking user feedback or acceptance criteria that contradict our tests. This could result in problems post-release, where real-world usage reveals issues that our tests did not catch.</p><p>🔧 <strong>Key Takeaways</strong>:</p><p>•	<strong>TDD</strong>, when applied thoughtfully, can significantly improve the quality and maintainability of your microservices.</p><p>•	Balancing test coverage with practical considerations is crucial to avoid overburdening the team with unnecessary tests.</p><p>•	Regularly revisiting and refactoring tests is as important as refactoring the production code to keep the test suite relevant and effective.</p><p>•	Always stay open to user feedback and be cautious of overestimating the efficacy of your tests — real-world scenarios can often expose unforeseen issues.</p><p>Implementing TDD in Spring Boot microservices has been a rewarding journey, despite the challenges. It’s a practice that has helped us build robust, scalable, and maintainable systems. If you’re considering TDD for your projects, be prepared for a learning curve, but know that the benefits are well worth the effort.</p><p>Would love to hear from others who have navigated the ups and downs of TDD in microservices! What strategies have worked for you?</p><p>#TDD #SpringBoot #Microservices #SoftwareEngineering #BackendDevelopment #CleanCode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c388302d137" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Harnessing the Power of TDD with MVVM in Mobile Development]]></title>
            <link>https://medium.com/@jameskong_35184/harnessing-the-power-of-tdd-with-mvvm-in-mobile-development-495cb1784cf6?source=rss-99992030b507------2</link>
            <guid isPermaLink="false">https://medium.com/p/495cb1784cf6</guid>
            <dc:creator><![CDATA[Computational Everything]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 05:54:18 GMT</pubDate>
            <atom:updated>2024-08-10T05:56:02.144Z</atom:updated>
            <content:encoded><![CDATA[<p>In my recent projects, I’ve found that combining Test-Driven Development (TDD) with the MVVM (Model-View-ViewModel) architecture has been a game-changer for building robust and maintainable mobile applications.</p><p>🔍 <strong>Why TDD?</strong></p><p>TDD forces us to think critically about the design and functionality before writing any code. By starting with tests, we’re better positioned to write clean, purposeful code that meets requirements from the get-go. It reduces bugs and gives us confidence that our code behaves as expected with each iteration.</p><p>🏛 <strong>Why MVVM?</strong></p><p>MVVM’s separation of concerns allows us to decouple business logic from UI code. The ViewModel acts as an intermediary between the Model (data) and the View (UI), making the code easier to test and maintain. This architecture complements TDD perfectly by making unit testing straightforward, ensuring that both our logic and UI interactions are bulletproof.</p><p>💡 <strong>My Takeaways:</strong></p><ol><li><strong>Testability</strong>: The combination of TDD with MVVM makes our codebase more testable. With clearly defined ViewModels, we can easily mock dependencies and write comprehensive tests.</li><li><strong>Maintainability</strong>: Separating concerns means we can modify the UI or business logic without disrupting other parts of the app. This leads to cleaner and more maintainable code.</li><li><strong>Confidence in Refactoring</strong>: With a solid suite of tests in place, refactoring becomes less risky. We can iterate and improve our code with the assurance that our tests will catch any regressions.</li></ol><p>Implementing TDD with MVVM isn’t without its challenges, but the benefits far outweigh the initial learning curve. It’s a methodology I’d recommend to any development team aiming for high-quality, maintainable code.</p><p>Would love to hear about others’ experiences with TDD and MVVM! What challenges have you faced, and how did you overcome them?</p><p>#TDD #MVVM #MobileDevelopment #CleanCode #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495cb1784cf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>