<?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 Ayesh Don on Medium]]></title>
        <description><![CDATA[Stories by Ayesh Don on Medium]]></description>
        <link>https://medium.com/@ayesh.don?source=rss-dcfee1f4aef1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*92nG3onu3aq30pdV.</url>
            <title>Stories by Ayesh Don on Medium</title>
            <link>https://medium.com/@ayesh.don?source=rss-dcfee1f4aef1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:04:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayesh.don/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[Offline First Architecture. Designing Mobile Apps That Never Wait for the Network]]></title>
            <link>https://medium.com/@ayesh.don/offline-first-architecture-designing-mobile-apps-that-never-wait-for-the-network-5fa4204e3610?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fa4204e3610</guid>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 15:51:22 GMT</pubDate>
            <atom:updated>2026-09-24T15:51:22.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mQEpoCHxR3HleZDqjhkxg.jpeg" /></figure><p>In today’s mobile landscape, users expect lightning-fast app responses regardless of whether they are sitting in a high-speed fiber optic office or riding a subway through a dead zone. Yet, many mobile applications are still designed with an “online-first” mentality making direct network calls, freezing the UI with loading spinners when connectivity drops, and leaving users stranded.</p><p>As a Senior Android Engineer, building modern, resilient applications means shifting our perspective entirely: treating the <strong>local device database as the absolute source of truth</strong>, and treating the network as a mere synchronization enhancement.</p><p>In this comprehensive guide, we’ll dive deep into Offline-First Architecture in Android, dissect its components, tackle core engineering challenges, and review practical code implementations using modern Android tech stacks</p><h3>1. What is “Offline-First”?</h3><p>An <strong>Offline-First</strong> architecture is a design paradigm where an application prioritizes local storage over network connectivity for reading and writing data.</p><p>Instead of an app fetching data directly from a remote server and caching it temporarily, an offline-first app <strong>always reads from and writes to a local database</strong> (e.g., SQLite/Room). A background sync engine then handles pushing local changes to the server and pulling remote updates whenever a network connection becomes available.</p><h3>2. Online-First vs. Offline-First: Why Make the Shift?</h3><h4>How “Online-First” Apps Work</h4><p>Traditional apps heavily rely on a synchronous request-response lifecycle</p><ul><li>User opens the app.</li><li>App triggers an HTTP GET request.</li><li>UI blocks or displays a shimmer/loading skeleton.</li><li>If the network fails or times out, the app throws an error dialog (“No Internet Connection”) and fails to load.</li></ul><h4>Advantages of Offline-First</h4><ul><li><strong>Instantaneous UI Rendering:</strong> Data loads instantly from local storage, dropping app startup latency close to zero.</li><li><strong>100% Offline Usability:</strong> Users can view, create, edit, and delete data even when completely offline.</li><li><strong>Network Resilience:</strong> Flaky cellular connections, switching from Wi-Fi to mobile data, or dead zones become completely transparent to the user experience.</li><li><strong>Reduced Server Load:</strong> Local caching minimizes redundant network round-trips.</li></ul><h4><em>Real-World App Examples</em></h4><ul><li><strong><em>Google Docs:</em></strong><em> You can type, edit notes, and create documents offline; everything syncs smoothly once back online.</em></li><li><strong><em>Spotify / Netflix:</em></strong><em> Media is downloaded locally for playback, while metadata syncs in the background.</em></li><li><strong><em>WhatsApp :</em></strong><em> Messages are instantly committed to local storage and marked with a pending sync indicator until delivered.</em></li></ul><h3>3. Core Architecture Flow: Local as Source of Truth &amp; Conflict Resolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS7y2ri-xKcGkewzcD-eIQ.jpeg" /></figure><h3>Local Data as the Single Source of Truth (SSOT)</h3><p>In a robust Android architecture, the UI layer never talks directly to the network or the DAO independently. Instead, the <strong>Repository</strong> acts as the single entry point.</p><ul><li>The UI observes a stream of data (using Kotlin Flow or LiveData) coming directly from the local database.</li><li>When the app fetches fresh data from the API, it <strong>does not</strong> pass it directly to the UI; it writes it to the local database first. The database update automatically propagates the new state to the UI via reactive streams.</li></ul><h4>Syncing with the Server</h4><p>Syncing requires a reliable strategy commonly implemented using a <strong>Queue-based Mutation Pattern</strong>:</p><ol><li><strong>Writes:</strong> When a user modifies data offline, the change is saved locally, and an entry is added to a local SyncQueue table (marking the item as isSynced = false).</li><li><strong>Push:</strong> When connectivity is restored, a background worker iterates through the SyncQueue, pushes changes to the server, and clears or marks items as synced upon success.</li><li><strong>Pull:</strong> Periodic or event-driven polling fetches server-side deltas and merges them locally.</li></ol><h4>Resolving Conflicts</h4><p>When two devices modify the same entity offline, conflicts arise. Common strategies include:</p><ul><li><strong>Last-Write-Wins (LWW):</strong> Using a client/server timestamp to accept the most recent modification.</li><li><strong>Client-Wins / Server-Wins:</strong> Hardcoded business rules.</li><li><strong>Advanced merging algorithms</strong> (ideal for collaborative document editing like google doc).</li></ul><h3>4. Engineering Challenges &amp; Solutions</h3><h4>1. Background Sync Battery &amp; Resource Management</h4><p>Constantly polling servers or running background sockets can drain battery quickly.</p><ul><li><strong>Solution:</strong> Use <strong>Jetpack WorkManager</strong>. It allows you to schedule deferrable, guaranteed background work based on specific constraints such as requiring an unmetered Wi-Fi connection and a charging device before running heavy batch synchronizations.</li></ul><h4>2. Performance Optimization on Android</h4><ul><li><strong>Indexing:</strong> Ensure frequently queried columns and foreign keys in your Room database are properly indexed.</li><li><strong>Pagination:</strong> Use <strong>Paging 3</strong> library locally to load large datasets incrementally, preventing UI jank and reducing memory overhead.</li></ul><h3>5. When to Use vs. When NOT to Use</h3><h4>When to Use</h4><ul><li>Apps with heavy user-generated content (notes, tasks, logs, e-commerce carts).</li><li>Apps targeted at users with intermittent or unreliable connectivity (field workers, commuters).</li><li>Collaborative workspaces requiring seamless multi-device state handling.</li></ul><h4>When NOT to Use</h4><ul><li>Real-time streaming or transactional applications where staleness is unacceptable (e.g., high frequency stock trading apps, live bidding platforms).</li><li>Systems dealing with extremely massive datasets that cannot fit locally on a mobile device and require server-side search/computation (e.g., multi-terabyte enterprise data warehouses).</li></ul><h3>6. Android Implementation: Code Example</h3><p>To complete our offline-first architecture blueprint, let’s look at how to implement a background synchronization mechanism for a <strong>Facebook like feed app</strong>.</p><p>In a social feed app, users often create posts, comment, or “like” content while offline. We save these actions locally immediately (for instant UI feedback), and use <strong>Jetpack WorkManager</strong> to sync them in the background safely and reliably once a network connection is restored.</p><h4>1. The WorkManager Worker (FeedSyncWorker)</h4><p>This worker checks the local database for any pending actions (like unsynced posts or reactions) and pushes them to the server.</p><pre>import android.content.Context<br>import androidx.work.CoroutineWorker<br>import androidx.work.WorkerParameters<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.withContext<br><br>class FeedSyncWorker(<br>    appContext: Context,<br>    workerParams: WorkerParameters,<br>    private val feedRepository: FeedRepository // Injected via Hilt/DI or manually<br>) : CoroutineWorker(appContext, workerParams) {<br><br>    override suspend fun doWork(): Result = withContext(Dispatchers.IO) {<br>        try {<br>            // 1. Fetch all pending local actions (e.g., offline posts/likes)<br>            val pendingActions = feedRepository.getUnsyncedActions()<br><br>            if (pendingActions.isEmpty()) {<br>                return@withContext Result.success()<br>            }<br><br>            // 2. Iterate and sync each action with the remote backend<br>            for (action in pendingActions) {<br>                val isSuccessful = feedRepository.syncActionToServer(action)<br>                if (isSuccessful) {<br>                    // Mark as synced locally so it isn&#39;t uploaded again<br>                    feedRepository.markActionAsSynced(action.id)<br>                } else {<br>                    // If any critical sync fails, retry later<br>                    return@withContext Result.retry()<br>                }<br>            }<br><br>            // 3. Optionally fetch latest feed items from server<br>            feedRepository.fetchAndRefreshFeed()<br><br>            Result.success()<br>        } catch (e: Exception) {<br>            // If network drops midway or server throws 5xx, retry with exponential backoff<br>            if (runAttemptCount &lt; 3) {<br>                Result.retry()<br>            } else {<br>                Result.failure()<br>            }<br>        }<br>    }<br>}</pre><h4>2. Enqueuing the Sync Work with Constraints</h4><p>You should trigger this worker whenever a user performs an offline action (like hitting “Post”) or periodically when connectivity changes. By leveraging WorkManager <strong>Constraints</strong>, we ensure the device doesn’t drain the battery trying to sync on a dead connection.</p><pre>import android.content.Context<br>import androidx.work.Constraints<br>import androidx.work.NetworkType<br>import androidx.work.ExistingWorkPolicy<br>import androidx.work.OneTimeWorkRequestBuilder<br>import androidx.work.WorkManager<br><br>object FeedSyncManager {<br><br>    private const val UNIQUE_SYNC_WORK_NAME = &quot;FeedSyncUniqueWork&quot;<br><br>    fun scheduleSync(context: Context) {<br>        // Define strict execution constraints<br>        val constraints = Constraints.Builder()<br>            .setRequiredNetworkType(NetworkType.CONNECTED) // Requires internet connection<br>            .build()<br><br>        val syncRequest = OneTimeWorkRequestBuilder&lt;FeedSyncWorker&gt;()<br>            .setConstraints(constraints)<br>            .build()<br><br>        // Enqueue unique work: if a sync is already pending, keep it; don&#39;t duplicate it.<br>        WorkManager.getInstance(context).enqueueUniqueWork(<br>            UNIQUE_SYNC_WORK_NAME,<br>            ExistingWorkPolicy.KEEP,<br>            syncRequest<br>        )<br>    }<br>}</pre><h4>3. Tying it together in the Repository</h4><p>When a user creates a post offline, you commit it locally and immediately trigger the sync manager,</p><pre>suspend fun createPost(content: String, context: Context) {<br>    val localPost = PostEntity(<br>        id = UUID.randomUUID().toString(),<br>        content = content,<br>        timestamp = System.currentTimeMillis(),<br>        isSynced = false // Pending sync<br>    )<br><br>    // 1. Save to Room database (UI instantly updates via Flow)<br>    postDao.insertPost(localPost)<br><br>    // 2. Add to the local sync action queue table<br>    syncDao.insertAction(SyncActionEntity(id = localPost.id, type = &quot;CREATE_POST&quot;))<br><br>    // 3. Kick off WorkManager to handle background synchronization<br>    FeedSyncManager.scheduleSync(context)<br>}</pre><blockquote><em>Why this approach shines for a Feed App</em></blockquote><blockquote><strong><em>Zero UI Blocking:</em></strong><em> The user posts a photo or status update, sees it appear in their feed timeline instantly, and can close the app without worrying.</em></blockquote><blockquote><strong><em>Guaranteed Execution:</em></strong><em> Even if the app crashes or the phone reboots, WorkManager preserves the task and executes it as soon as the network returns.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fa4204e3610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart App Alerts. App Update Strategies & Maintenance UX]]></title>
            <link>https://medium.com/@ayesh.don/smart-app-alerts-app-update-strategies-maintenance-ux-8b3a0c035866?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b3a0c035866</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[andoid]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 06:44:54 GMT</pubDate>
            <atom:updated>2026-04-06T06:44:54.172Z</atom:updated>
            <content:encoded><![CDATA[<p>In mobile development, the ability to communicate with your users outside of the standard UI flow is critical. Whether it’s a mandatory security patch, a seasonal greeting, or a localised feature maintenance window, your architecture must be robust enough to handle these triggers even when your primary API fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NK-CgwovQ05RD6SuRVDufQ.png" /></figure><h4><strong>Why App Update Management Matters More Than You Think</strong></h4><p>This is a deepdive for mobile engineers who have been burned by the usual approaches. We are covering everything, force update via your own backend, force update via Firebase Remote Config (and <em>why</em> you need both), feature level updates, session greeting alerts, maintenance banners, and <em>micro service</em> level maintenance UX. We will also talk architecture and <em>real world</em> failure modes including the SSL pinning incident that made Firebase our safety net.</p><ol><li><strong>Force Update — The SSL Pinning Wake-Up Call</strong></li></ol><p>A common pitfall is relying solely on a custom backend API for force updates. If your API becomes unreachable for instance, due to an <strong>unforeseen SSL certificate rotation</strong> that breaks your <strong>SSL Pinning, </strong>your app effectively becomes a “brick.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFKH3F7-RWwMdygehY_2Iw.png" /><figcaption>Dual-Trigger Force Update Architecture</figcaption></figure><h4><strong><em>The Dual-Trigger Architecture</em></strong></h4><p>The key design decision is OR logic. if either source signals a force update, the screen is shown. You never need both to agree. This means Firebase RC alone can block a broken version even when your backend is unreachable.</p><p>Note : <br>1. <strong>Primary (REST API):</strong> Your app hits a /config or /version endpoint on startup. This allows for complex logic,<em> such as targeting specific user segments or regions.</em></p><p>2. <strong>Secondary (Firebase Remote Config):</strong> This acts as your “Fail-Safe.” Since Firebase uses its own secure connection independent of your private SSL pinning implementation, you can toggle a force_update_required flag here to rescue users when your primary backend is down.</p><p>Pseudo-code</p><pre>fun checkUpdateStatus() {<br>    // 1. Try Primary API<br>    val apiResponse = repository.fetchAppConfig()<br>    <br>    // just to demo apiResponse != null. you can add your own logic here<br>    if (apiResponse != null) {<br>        handleLogic(apiResponse.minVersion)<br>    } else {<br>        // 2. Fail-safe: Check Firebase Remote Config<br>        val minVersionFromFirebase = FirebaseRemoteConfig.getInstance().getString(&quot;min_version&quot;)<br>        handleLogic(minVersionFromFirebase)<br>    }<br>}</pre><h4><strong><em>Feature-Level Maintenance: The Header Strategy</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rspGUqkR4K7SbYCazT1YfQ.png" /><figcaption>Feature-Level Maintenance</figcaption></figure><p>Total app blackouts during maintenance are frustrating for users. If only your “Payment” microservice is under maintain, the rest of the app should remain functional.</p><ul><li><strong>Logic:</strong> The mobile app uses an Interceptor to check for a specific header (e.g. X-Feature-Maintenance: true).</li><li><strong>Action:</strong> If the header is detected, the app reactively disables only the “Payment” button and shows a localised <strong>Feature Maintenance Banner(alert)</strong>.</li></ul><p><strong><em>Global vs. Feature Maintenance</em></strong></p><blockquote><strong>Maintenance Type: Global</strong> Trigger: 503 Service Unavailable → UI: Full-screen overlay blocking all interactions</blockquote><blockquote><strong>Maintenance Type: Feature-Specific</strong> Trigger: X-Feature-Maintenance header → UI: Inline banner at the top of the affected module</blockquote><h4>Version-Based Content Filtering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8NKMkFotKAmn0p5EzScFQ.png" /><figcaption>Header-Based Version Gate Flow</figcaption></figure><p>Sometimes, a legacy app version cannot support a new data schema. Instead of a global force update, you can implement <strong>Feature Wise Force Updates</strong>.</p><p><strong>The Logic:</strong> When the app requests data, the backend checks the User-Agent or a custom X-App-Version header. If the version is too low for that specific feature,</p><ol><li>The backend returns a <strong>426 Upgrade Required</strong> status.</li><li>The response body contains a specific JSON payload: {&quot;reason&quot;: &quot;feature_update&quot;, &quot;message&quot;: &quot;This feature requires version 2.0&quot;}.</li><li>The app intercepts this and shows a targeted update popup instead of the content.</li></ol><h4>Seasonal and Informational Alerts</h4><p>For <strong>Seasonal and Informational Alerts</strong>, the goal is flexibility. Unlike a hardcoded greeting, using <strong>Firebase Remote Config</strong> allows you to trigger a “Happy New Year” banner or a “Holiday Sale” alert instantly without a new App Store/Play Store submission.</p><h3>The Logic Flow</h3><ol><li><strong>Fetch Config:</strong> The app fetches a JSON object from Firebase.</li><li><strong>Validate Date:</strong> The app checks if today’s date falls within the start_date and end_date defined in the config.</li><li><strong>Frequency Check:</strong> To avoid annoying users, we use a local flag (SharedPreferences/DataStore) to ensure the alert only shows once per session or once ever.</li></ol><p><em>Note : You can expand on this reasoning as you see fit please just provide the fundamental logic</em></p><p>Firebase Remote Config Setup</p><pre>{<br>  &quot;id&quot;: &quot;ramadan_2026&quot;,<br>  &quot;title&quot;: &quot;Ramadan Kareem!&quot;,<br>  &quot;message&quot;: &quot;Wishing you a blessed month. Check out our special features.&quot;,<br>  &quot;image_url&quot;: &quot;https://cdn.example.com/banners/ramadan.png&quot;,<br>  &quot;start_date&quot;: &quot;2026-03-10T00:00:00Z&quot;,<br>  &quot;end_date&quot;: &quot;2026-04-09T23:59:59Z&quot;,<br>  &quot;priority&quot;: 3,<br>  &quot;is_active&quot;: true<br>}</pre><p>Mobile Implementation (Pseudo-code)</p><pre>class AlertManager(private val remoteConfig: FirebaseRemoteConfig) {<br><br>    fun checkAndShowSeasonalAlert(context: Context) {<br>        // 1. Fetch and Activate latest config<br>        remoteConfig.fetchAndActivate().addOnCompleteListener { task -&gt;<br>            if (task.isSuccessful) {<br>                val jsonString = remoteConfig.getString(&quot;seasonal_alert_config&quot;)<br>                val config = parseJson&lt;SeasonalAlert&gt;(jsonString)<br><br>                if (shouldShowAlert(config)) {<br>                    showBannerUI(config)<br>                    markAsShown(config.id)<br>                }<br>            }<br>        }<br>    }<br><br>    private fun shouldShowAlert(config: SeasonalAlert): Boolean {<br>        val now = Date()<br>        <br>        // 2. Logic Gates<br>        val isInDateRange = now.after(config.startDate) &amp;&amp; now.before(config.endDate)<br>        val isNotShownYet = !LocalPrefs.isAlertDismissed(config.id)<br>        <br>        return config.isActive &amp;&amp; isInDateRange &amp;&amp; isNotShownYet<br>    }<br><br>    private fun showBannerUI(config: SeasonalAlert) {<br>        // 3. UI Logic (Bottom Sheet or Top Banner)<br>        AlertUI.builder()<br>            .setTitle(config.title)<br>            .setBody(config.message)<br>            .setImage(config.imageUrl)<br>            .setPositiveButton(&quot;Explore&quot;) { <br>                // Navigate to specific feature<br>            }<br>            .show()<br>    }<br>}</pre><p><strong>Handling Multiple Alert Priorities<br></strong>When you have both a <strong>Force Update</strong> and a <strong>Seasonal Greeting</strong>, the architecture must prioritize.</p><pre>fun handleAllAlerts() {<br>    // Priority 1: Force Update (Critical)<br>    if (checkForceUpdate()) return // Stop here if update is required<br><br>    // Priority 2: System Maintenance<br>    if (checkMaintenanceHeader()) return<br><br>    // Priority 3: Seasonal Greetings (Informational)<br>    checkAndShowSeasonalAlert()<br>}</pre><p><strong><em>Best Practices &amp; Lessons Learned</em></strong></p><ul><li><strong>Never Hardcode Logic:</strong> Always drive UI strings (messages) from the backend/Firebase so you can translate or update them without a new build.</li><li><strong>Graceful Degradation:</strong> If the “Greeting” API fails, the app should simply open as normal. Alerts are “nice-to-haves,” but the app’s core functionality is a “must-have.”</li><li><strong>The SSL Lesson:</strong> Always have a “backdoor” config (like Firebase) that doesn’t share your main API’s certificate infrastructure. It saves your user base during infrastructure migrations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b3a0c035866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Flutter BLoC Pattern with Clean Architecture]]></title>
            <link>https://medium.com/@ayesh.don/mastering-flutter-bloc-pattern-with-clean-architecture-030c2df3051c?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/030c2df3051c</guid>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 07:25:30 GMT</pubDate>
            <atom:updated>2026-03-09T07:25:30.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpUO7XxxfrhRN6qMmer0MQ.jpeg" /></figure><p>State management is one of the most crucial aspects of Flutter development. The flutter_bloc package, based on the Business Logic Component (BLOC) pattern, provides a robust, predictable, and scalable way to handle your application&#39;s state. It perfectly complements <strong>Clean Architecture</strong> and <strong>SOLID Principles</strong>, leading to code that is easy to test, maintain, and extend.<br>In this Article comprehensive guide, will build a Flutter weather application that fetches data from a real weather API and displays it in a list. We will focus on.</p><ul><li><strong>Cubit Pattern:</strong> A simpler version of BLoC.</li><li><strong>BLoC Pattern:</strong> The full-featured event-driven pattern.</li><li><strong>Clean Architecture:</strong> Organizing our code into distinct layers (Data, Domain, Presentation).</li><li><strong>Best Practices:</strong> Following SOLID principles for clean and maintainable code.</li><li><strong>Key BLoC Components:</strong> Explaining BlocObserver, BlocBuilder, onChange, onError, and BlocProvider.</li></ul><p>By the end of this tutorial, you will have a deep understanding of how to manage complex state in a large scale Flutter application using BLOC.</p><h3><strong>The Core Concept( BLoC vs. Cubit )</strong></h3><p>Before diving into more, let’s understand the two main concepts provided by the flutter_bloc package.</p><h4>Cubit Pattern</h4><p>Cubit is a simpler way to manage state. It exposes <em>functions</em> that directly emit new states. It&#39;s a great choice for simpler state management scenarios, like toggling a switch, a simple counter, or a one-off data fetch where advanced event transformations are not required.</p><p><strong>Pros of Cubit:</strong></p><ul><li>Simpler API (fewer components).</li><li>Less boilerplate.</li><li>Ideal for basic, function-driven state changes.</li></ul><p><strong>Cons of Cubit:</strong></p><ul><li>Does not support advanced event transformations (like debounce, throttle).</li><li>Events are not tracked, making the state transition history less explicit in some advanced debugging scenarios.</li></ul><h3>BLoC Pattern</h3><p>BLoC (Business Logic Component) is event-driven. Instead of calling functions, widgets emit <em>events</em> to the BLoC. The BLoC then processes these events using on&lt;Event&gt; handlers and emits new <em>states</em>.</p><p><strong>Pros of BLoC:</strong></p><ul><li><strong>Event-driven:</strong> Provides a clear separation between <em>what happened</em> (events) and <em>what to do</em> (logic).</li><li><strong>Highly testable:</strong> You test the BLoC by asserting the states emitted in response to events.</li><li><strong>Advanced Features:</strong> Supports powerful event transformations (using RxDart operators like debounceTime, switchMap).</li><li><strong>Explicit State Transitions:</strong> The entire history of events and their resulting states is explicit.</li></ul><p><strong>Cons of BLoC:</strong></p><ul><li>More boilerplate than Cubit (requires defining events, states, and event handlers).</li><li>Slightly steeper learning curve.</li></ul><h3>Which to Choose?</h3><ul><li>Start with <strong>Cubit</strong> for simple features and one-off actions.</li><li>Switch to <strong>BLoC</strong> when you need:</li><li>Event-driven logic.</li><li>Complex event transformations (e.g., search with debounce).</li><li>A clearer history of events for auditing or debugging.</li></ul><h3>Clean Architecture Structure</h3><p>To ensure our app is scalable and maintainable, we’ll follow a simplified Clean Architecture structure. This separates concerns into distinct layers,</p><h3>Why Clean Architecture?</h3><ul><li><strong>Testability:</strong> You can test business logic (domain) independently of the UI and data sources.</li><li><strong>Maintainability:</strong> Changes in one layer (e.g., changing API provider) don’t affect other layers.</li><li><strong>Scalability:</strong> The structure naturally accommodates new features and complexity.</li><li><strong>Independence:</strong> The core logic isn’t tied to the UI framework or specific external libraries.</li></ul><h3>SOLID Principles</h3><p>Our implementation will align with SOLID principles,</p><ul><li><strong>Single Responsibility Principle (SRP):</strong> Each class (Repository, BLoC, Model) has only one reason to change.</li><li><strong>Open/Closed Principle (OCP):</strong> Our repository interface allows for new data sources without modifying existing logic.</li><li><strong>Liskov Substitution Principle (LSP):</strong> Our implementation can replace the abstraction without issues.</li><li><strong>Interface Segregation Principle (ISP):</strong> (Implicitly followed by simple interfaces).</li><li><strong>Dependency Inversion Principle (DIP):</strong> Presentation layer (BLoC) depends on abstract repositories (Domain), not concrete implementations (Data).</li></ul><h3>Weather API Integration Example</h3><p>We will use the OpenWeatherMap API for this example. Sign up for a free account to get your API key. We’ll build a simplified app that fetches weather for a predefined city.</p><h4>Project Setup and Dependencies</h4><p>Add the following to your pubspec.yaml</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.1.0     <br>  bloc: ^8.1.0<br>  equatable: ^2.0.5          <br>  dio: ^5.3.3             <br>  intl: ^0.18.1          </pre><h4>Implementation: Data Layer</h4><pre>class WeatherModel extends Equatable {<br>  final String cityName;<br>  final double temperature;<br>  final String condition;<br>  final String icon;<br><br>  const WeatherModel({<br>    required this.cityName,<br>    required this.temperature,<br>    required this.condition,<br>    required this.icon,<br>  });<br><br>  factory WeatherModel.fromJson(Map&lt;String, dynamic&gt; json) {<br>    return WeatherModel(<br>      cityName: json[&#39;name&#39;],<br>      temperature: json[&#39;main&#39;][&#39;temp&#39;].toDouble(),<br>      condition: json[&#39;weather&#39;][0][&#39;main&#39;],<br>      icon: json[&#39;weather&#39;][0][&#39;icon&#39;],<br>    );<br>  }<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [cityName, temperature, condition, icon];<br>}</pre><blockquote><strong>Note:</strong> Equatable is crucial. It ensures that two WeatherModel instances with the same values are considered equal. This is <em>vital</em> for BLoC because it won&#39;t emit a new state if the <em>new</em> state is equal to the <em>old</em> state, preventing unnecessary UI repaints</blockquote><h4>Weather Repository Interface</h4><pre>abstract class WeatherRepository {<br>  Future&lt;WeatherModel&gt; getWeather(String cityName);<br>}</pre><h4>Weather Repository Implementation</h4><pre>class WeatherRepositoryImpl implements WeatherRepository {<br>  final Dio _dio;<br>  final String _apiKey = &#39;YOUR_API_KEY_HERE&#39;;<br>  final String _baseUrl = &#39;https://api.openweathermap.org/data/2.5/&#39;;<br><br>  WeatherRepositoryImpl({Dio? dio}) : _dio = dio ?? Dio();<br><br>  @override<br>  Future&lt;WeatherModel&gt; getWeather(String cityName) async {<br>    try {<br>      final response = await _dio.get(<br>        &#39;${_baseUrl}weather&#39;,<br>        queryParameters: {<br>          &#39;q&#39;: cityName,<br>          &#39;appid&#39;: _apiKey,<br>          &#39;units&#39;: &#39;metric&#39;,<br>        },<br>      );<br><br>      if (response.statusCode == 200) {<br>        return WeatherModel.fromJson(response.data);<br>      } else {<br>        throw Exception(&#39;Failed to load weather&#39;);<br>      }<br>    } catch (e) {<br>      throw Exception(&#39;Error fetching weather: $e&#39;);<br>    }<br>  }<br>}</pre><h4>Implementation: Domain Layer</h4><p>In this example, we directly use the abstract repository in the BLoC for simplicity. <strong>For larger projects, you would introduce Use Cases here.</strong></p><p>If we added a Use Case, the structure would change like this</p><pre>class GetWeather {<br>  final WeatherRepository repository;<br><br>  GetWeather(this.repository);<br><br>  Future&lt;WeatherModel&gt; execute(String cityName) {<br>    return repository.getWeather(cityName);<br>  }<br>}</pre><h4>Implementation: Presentation Layer</h4><blockquote>Weather Cubit Example</blockquote><pre>abstract class WeatherCubitState extends Equatable {<br>  const WeatherCubitState();<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class WeatherCubitInitial extends WeatherCubitState {}<br>class WeatherCubitLoading extends WeatherCubitState {}<br>class WeatherCubitLoaded extends WeatherCubitState {<br>  final WeatherModel weather;<br>  const WeatherCubitLoaded(this.weather);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [weather];<br>}<br>class WeatherCubitError extends WeatherCubitState {<br>  final String message;<br>  const WeatherCubitError(this.message);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [message];<br>}<br><br>class WeatherCubit extends Cubit&lt;WeatherCubitState&gt; {<br>  final WeatherRepository repository;<br><br>  WeatherCubit(this.repository) : super(WeatherCubitInitial());<br><br>  Future&lt;void&gt; fetchWeather(String cityName) async {<br>    try {<br>      emit(WeatherCubitLoading());<br>      final weather = await repository.getWeather(cityName);<br>      emit(WeatherCubitLoaded(weather));<br>    } catch (e) {<br>      emit(WeatherCubitError(e.toString()));<br>    }<br>  }<br>}</pre><blockquote>Weather BLoC Example (Event-Driven)</blockquote><pre>abstract class WeatherEvent extends Equatable {<br>  const WeatherEvent();<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class LoadWeather extends WeatherEvent {<br>  final String cityName;<br>  const LoadWeather(this.cityName);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [cityName];<br>}<br><br>class RefreshWeather extends WeatherEvent {<br>    final String cityName;<br>  const RefreshWeather(this.cityName);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [cityName];<br>}<br><br><br>abstract class WeatherBlocState extends Equatable {<br>  const WeatherBlocState();<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class WeatherBlocInitial extends WeatherBlocState {}<br>class WeatherBlocLoading extends WeatherBlocState {}<br>class WeatherBlocLoaded extends WeatherBlocState {<br>  final WeatherModel weather;<br>  const WeatherBlocLoaded(this.weather);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [weather];<br>}<br>class WeatherBlocError extends WeatherBlocState {<br>  final String message;<br>  const WeatherBlocError(this.message);<br>  @override<br>  List&lt;Object&gt; get props =&gt; [message];<br>}<br><br>class WeatherBloc extends Bloc&lt;WeatherEvent, WeatherBlocState&gt; {<br>  final WeatherRepository repository;<br><br>  WeatherBloc(this.repository) : super(WeatherBlocInitial()) {<br>    on&lt;LoadWeather&gt;(_onLoadWeather);<br>    on&lt;RefreshWeather&gt;(_onRefreshWeather);<br>  }<br><br>  Future&lt;void&gt; _onLoadWeather(LoadWeather event, Emitter&lt;WeatherBlocState&gt; emit) async {<br>      try {<br>        emit(WeatherBlocLoading());<br>        final weather = await repository.getWeather(event.cityName);<br>        emit(WeatherBlocLoaded(weather));<br>      } catch (e) {<br>        emit(WeatherBlocError(e.toString()));<br>      }<br>  }<br><br>  Future&lt;void&gt; _onRefreshWeather(RefreshWeather event, Emitter&lt;WeatherBlocState&gt; emit) async {<br>      try {<br>        final weather = await repository.getWeather(event.cityName);<br>        emit(WeatherBlocLoaded(weather));<br>      } catch (e) {<br>       ]emit(WeatherBlocError(e.toString()));<br>      }<br>  }<br>}</pre><h3>Advanced BLoC Features Explained</h3><h4>BlocObserver</h4><p>A global listener for all events, states, and errors in all BLoCs and Cubits in your app. It’s powerful for logging, analytics, and debugging.</p><pre>class AppBlocObserver extends BlocObserver {<br>  @override<br>  void onCreate(BlocBase bloc) {<br>    super.onCreate(bloc);<br>    if (kDebugMode) print(&#39;onCreate -- ${bloc.runtimeType}&#39;);<br>  }<br><br>  @override<br>  void onEvent(Bloc bloc, Object? event) {<br>    super.onEvent(bloc, event);<br>    if (kDebugMode) print(&#39;onEvent -- ${bloc.runtimeType}, event: $event&#39;);<br>  }<br><br>  @override<br>  void onChange(BlocBase bloc, Change change) {<br>    super.onChange(bloc, change);<br>    if (kDebugMode) {<br>      print(&#39;onChange -- ${bloc.runtimeType}, change: { currentState: ${change.currentState}, nextState: ${change.nextState} }&#39;);<br>    }<br>  }<br><br>  @override<br>  void onTransition(Bloc bloc, Transition transition) {<br>    super.onTransition(bloc, transition);<br>    if (kDebugMode) {<br>      print(&#39;onTransition -- ${bloc.runtimeType}, transition: { event: ${transition.event}, currentState: ${transition.currentState}, nextState: ${transition.nextState} }&#39;);<br>    }<br>  }<br><br>  @override<br>  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {<br>    if (kDebugMode) print(&#39;onError -- ${bloc.runtimeType}, error: $error&#39;);<br>    super.onError(bloc, error, stackTrace);<br>  }<br><br>  @override<br>  void onClose(BlocBase bloc) {<br>    super.onClose(bloc);<br>    if (kDebugMode) print(&#39;onClose -- ${bloc.runtimeType}&#39;);<br>  }<br>}<br><br>//main.dart<br><br>void main() {<br>  Bloc.observer = AppBlocObserver();<br>  runApp(const MyApp());<br>}</pre><h4>BlocBuilder</h4><p>A Flutter widget that rebuilds itself in response to new states. It’s the most common way to build UI from BLoC states. It takes a builder function which is called whenever the state changes.</p><pre>BlocBuilder&lt;WeatherBloc, WeatherBlocState&gt;(<br>  builder: (context, state) {<br>    if (state is WeatherBlocLoading) {<br>      return const Center(child: CircularProgressIndicator());<br>    } else if (state is WeatherBlocLoaded) {<br>      return _buildWeatherInfo(state.weather);<br>    } else if (state is WeatherBlocError) {<br>      return Center(child: Text(&#39;Error: ${state.message}&#39;));<br>    }<br>    return const Center(child: Text(&#39;Please load weather.&#39;));<br>  },<br>)</pre><p><strong>Key feature: </strong><strong>buildWhen:</strong></p><p>A vital best practice for performance is using buildWhen. It&#39;s an optional function that decides whether BlocBuilder should rebuild its content. This prevents unnecessary UI repaints when irrelevant states are emitted.</p><pre>BlocBuilder&lt;WeatherBloc, WeatherBlocState&gt;(<br>  buildWhen: (previousState, currentState) {<br>    return previousState is WeatherBlocLoaded || currentState is WeatherBlocLoaded ||<br>           previousState is WeatherBlocError || currentState is WeatherBlocError;<br>  },<br>  builder: (context, state) { ... }<br>)</pre><h4>BlocProvider and MultiBlocProvider</h4><p>A widget that provides an instance of a BLoC/Cubit to its children using the Provider pattern. This is crucial for <strong>dependency injection (DI)</strong> within the widget tree.</p><p><strong>Usage:</strong></p><ul><li><strong>Single Provider:</strong> Used at the root of a page (or feature) to provide one BLoC.</li><li><strong>MultiBlocProvider:</strong> Vital when a widget tree depends on multiple BLoCs. Instead of nesting multiple BlocProvider widgets, MultiBlocProvider improves code readability and structure.</li></ul><p><strong>Best Practice: Where to use?</strong></p><p>It is <strong>NOT</strong> a best practice to put <em>all</em> BlocProviders at the root main.dart if those BLoCs are only needed for specific pages.</p><ul><li><strong>Global BLoCs:</strong> BLoCs required app-wide (e.g., AuthenticationBloc, ThemeCubit, UserLocaleCubit) should be provided in main.dart.</li><li><strong>Feature BLoCs:</strong> BLoCs that only exist within the context of a feature (e.g., WeatherBloc for the weather page, ShoppingCartBloc) should be provided at the root widget of <em>that specific page</em>. This ensures the BLoC is created when the page opens and properly closed when the page is popped from the stack, saving resources.</li></ul><h4><strong><em>Building the UI: Weather Page and Widgets</em></strong></h4><pre>class WeatherView extends StatefulWidget {<br>  const WeatherView({super.key});<br><br>  @override<br>  State&lt;WeatherView&gt; createState() =&gt; _WeatherViewState();<br>}<br><br>class _WeatherViewState extends State&lt;WeatherView&gt; {<br>  final _cityController = TextEditingController(text: &#39;London&#39;);<br><br>  @override<br>  void dispose() {<br>    _cityController.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        Padding(<br>          padding: const EdgeInsets.all(16.0),<br>          child: Row(<br>            children: [<br>              Expanded(<br>                child: TextField(<br>                  controller: _cityController,<br>                  decoration: const InputDecoration(labelText: &#39;Enter City&#39;),<br>                ),<br>              ),<br>              IconButton(<br>                icon: const Icon(Icons.search),<br>                onPressed: () {<br>                  final cityName = _cityController.text.trim();<br>                  if (cityName.isNotEmpty) {<br>                    context.read&lt;WeatherBloc&gt;().add(LoadWeather(cityName));<br>                  }<br>                },<br>              ),<br>            ],<br>          ),<br>        ),<br>        Expanded(<br>          child: BlocBuilder&lt;WeatherBloc, WeatherBlocState&gt;(<br>            buildWhen: (previousState, currentState) {<br>              return currentState is WeatherBlocLoaded ||<br>                  currentState is WeatherBlocError ||<br>                  currentState is WeatherBlocInitial;<br>            },<br>            builder: (context, state) {<br>              if (state is WeatherBlocInitial) {<br>                return const Center(child: Text(&#39;Search for a city\&#39;s weather&#39;));<br>              } else if (state is WeatherBlocLoading) {<br>                return const Center(child: CircularProgressIndicator());<br>              } else if (state is WeatherBlocLoaded) {<br>                return WeatherDisplayWidget(weather: state.weather);<br>              } else if (state is WeatherBlocError) {<br>                return Center(<br>                  child: Text(<br>                    &#39;Error: ${state.message}&#39;,<br>                    style: const TextStyle(color: Colors.red),<br>                    textAlign: TextAlign.center,<br>                  ),<br>                );<br>              }<br>              return const Container(); <br>            },<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>Details page</p><pre>class WeatherDisplayWidget extends StatelessWidget {<br>  final WeatherModel weather;<br><br>  const WeatherDisplayWidget({super.key, required this.weather});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SingleChildScrollView(<br>      physics: const AlwaysScrollableScrollPhysics(),<br>      child: Card(<br>        margin: const EdgeInsets.all(16.0),<br>        child: Padding(<br>          padding: const EdgeInsets.all(24.0),<br>          child: Column(<br>            mainAxisSize: MainAxisSize.min,<br>            children: [<br>              Text(<br>                weather.cityName,<br>                style: Theme.of(context).textTheme.headlineMedium,<br>              ),<br>              const SizedBox(height: 16),<br>              Image.network(<br>                &#39;@4x.png&#39;&quot;&gt;https://openweathermap.org/img/wn/${weather.icon}@4x.png&#39;,<br>                height: 100,<br>                width: 100,<br>                errorBuilder: (ctx, _, __) =&gt; const Icon(Icons.error, size: 100),<br>              ),<br>              const SizedBox(height: 16),<br>              Text(<br>                &#39;${weather.temperature.toStringAsFixed(1)}°C&#39;,<br>                style: Theme.of(context).textTheme.displayLarge,<br>              ),<br>              const SizedBox(height: 16),<br>              Text(<br>                weather.condition,<br>                style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4>Performance Best Practices Summary</h4><ul><li><strong>Use Equatable:</strong> Essential for efficient state comparison and preventing unnecessary UI repaints.</li><li><strong>Implement </strong><strong>buildWhen in </strong><strong>BlocBuilder:</strong> Granular control over widget rebuilds for optimal performance.</li><li><strong>Scope BLoCProviders appropriately:</strong> Create feature BLoCs at the page level, not the app level, so they are properly closed. Use MultiBlocProvider for multiple BLoCs in one tree.</li><li><strong>Handle Errors with </strong><strong>onError:</strong> Never let exceptions crash your app. Log them in BlocObserver or handle them gracefully in BlocListener/BlocBuilder.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=030c2df3051c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Magic Behind Kotlin Coroutine Call Stacks]]></title>
            <link>https://medium.com/@ayesh.don/understanding-the-magic-behind-kotlin-coroutine-call-stacks-18f3b41dee36?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f3b41dee36</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 04:14:30 GMT</pubDate>
            <atom:updated>2025-11-05T04:14:30.509Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re new to coroutines, it can feel magical — <em>“suspend functions pause and resume… but how does the call stack even work?”</em> 🤔</p><p>Kotlin Coroutines have revolutionized asynchronous programming, making complex concurrent tasks feel synchronous and easy to manage. But beneath the surface, how do they actually handle their “non-blocking” nature and manage their execution flow without traditional blocking? The key lies in understanding their unique approach to the call stack.</p><p>In traditional Java or Kotlin functions, the <strong>call stack</strong> grows and shrinks as functions call each other.But coroutines work differently, they <strong>suspend</strong> without blocking threads, and the <strong>call stack is restored</strong> when the coroutine resumes.</p><h3>Example: Three Suspend Functions</h3><pre>import kotlinx.coroutines.*<br><br>suspend fun fetchData(): String {<br>    println(&quot;Fetching data...&quot;)<br>    delay(1000)<br>    return &quot;Data from server&quot;<br>}<br><br>suspend fun processData(): String {<br>    println(&quot;Processing data...&quot;)<br>    val data = fetchData()<br>    return &quot;Processed: $data&quot;<br>}<br><br>suspend fun showResult() {<br>    println(&quot;Showing result...&quot;)<br>    val result = processData()<br>    println(result)<br>}<br><br>fun main() = runBlocking {<br>    showResult()<br>}</pre><h4>Step 1: Initial Call (Before Any Suspension)</h4><p>When main() starts a coroutine using runBlocking, it immediately calls showResult().</p><p>At this moment, the call stack looks just like a normal synchronous function chain</p><h4>Step 2: When delay() Suspends</h4><p>Now, inside fetchData(), the coroutine hits delay(1000).Here’s where the coroutine magic begins</p><ul><li>The coroutine <strong>suspends</strong>.</li><li>The <strong>current thread is freed</strong>.</li><li>The <strong>call stack is not destroyed</strong> but <strong>captured</strong> as a <em>continuation</em>.</li></ul><p>In simple terms,the state of the coroutine (local variables, next instruction, etc.) is saved.</p><p>The physical thread call stack clears up, but Kotlin keeps a logical structure of the stack to resume later.</p><h4>Step 3: Resumption After Delay</h4><p>After the 1-second delay, the coroutine resumes on a thread (maybe the same one, maybe different).</p><p>Kotlin restores the continuation,</p><ul><li>fetchData() resumes from after the delay() call and returns &quot;Data from server&quot;.</li><li>processData() resumes and returns &quot;Processed: Data from server&quot;.</li><li>showResult() resumes and prints &quot;Processed: Data from server&quot;.</li></ul><h4>Under the Hood: Continuation Objects</h4><p>Under the hood, Kotlin uses <strong>state machines</strong> and <strong>continuation objects</strong> to manage this process.Each suspend function is compiled into a state machine that knows,</p><ul><li>Where to resume (label or state number)</li><li>Local variable values</li><li>The next function to call</li></ul><p>This means you can have deep suspending chains even recursive ones without blocking the thread or blowing up the stack.</p><p><strong>Key Takeaways:</strong></p><ul><li>Kotlin coroutines <em>don’t block threads</em> — they <em>suspend and resume</em>.</li><li>The <em>call stack</em> is saved as a <strong>continuation</strong>, not kept on the thread.</li><li>Upon resumption, Kotlin reconstructs the logical call stack step-by-step.</li></ul><p>Kotlin Coroutines provide an elegant abstraction for asynchronous programming. By understanding that suspend functions don&#39;t block the thread but rather <em>suspend</em> and <em>resume</em> by saving and restoring their execution context (Continuation-Passing Style), you can grasp the true power behind their non-blocking nature. This allows for highly efficient and scalable concurrent applications without the complexities of traditional callbacks or explicit thread management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f3b41dee36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Cohesive Mobile Experiences: A Strategy for Reusable UI Components]]></title>
            <link>https://medium.com/@ayesh.don/crafting-cohesive-mobile-experiences-a-strategy-for-reusable-ui-components-192205fd90ea?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/192205fd90ea</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 04:39:28 GMT</pubDate>
            <atom:updated>2025-09-19T04:39:28.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9F8Mz07kWyDDV06FsazBg.png" /></figure><p>In the fast-paced world of mobile app development, user expectations are higher than ever. Users demand intuitive, visually appealing, and consistent experiences across every screen. For developers and designers, this often means grappling with maintaining consistency, speeding up development, and simplifying future updates.</p><p>If you’re planning a mobile app revamp, or even starting fresh, a well-defined strategy for reusable UI components is paramount. This article outlines a powerful hierarchical approach — one that moves from atomic “CHILD” to complex “Root Views” — ensuring consistency, accelerating development, and fostering a scalable codebase.</p><h4>The Challenge: Inconsistent UIs and Development Bottlenecks</h4><p>Many existing mobile apps suffer from a lack of a cohesive UI strategy. Developers might create custom UI elements for each screen, leading to,</p><ul><li><strong>Inconsistency:</strong> Buttons, text styles, and cards might look slightly different across various parts of the app, creating a disjointed user experience.</li><li><strong>Slow Development:</strong> Every new feature requires building UI elements from scratch, increasing development time.</li><li><strong>Maintenance Headaches:</strong> Changing a design element means hunting down and modifying it in numerous places.</li><li><strong>Bloated Codebase:</strong> Duplicated code for similar UI elements makes the app larger and harder to manage.</li></ul><p>Developer goal is to overcome these challenges by establishing a clear, layered approach to UI component creation.</p><h4>Proposed Hierarchy: Child, Widget, and Root View</h4><p>Suggested hierarchy is spot-on and forms the backbone of a robust design system. Let’s break it down and expand on each level.</p><h4>1. Child: The Atomic Element</h4><p>At the lowest level, “CHILD” are your atomic UI components. These are the smallest, indivisible building blocks that carry specific styles and behaviors. They are highly generic and can be used across the entire application without modification.</p><p><strong>Examples of Children:</strong></p><ul><li><strong>Common Text View:</strong> Defined text styles (e.g., headline1, bodyText, caption).</li><li><strong>Common Text Field:</strong> Standardized input fields with consistent borders, padding, and error states.</li><li><strong>Common Button:</strong> Primary, secondary, outline buttons with consistent padding, typography, and corner radius.</li></ul><p><strong>Considerations for Children:</strong></p><ul><li><strong>Style Guide Integration:</strong> Each child should directly reflect your app’s design system’s typography, color palette, spacing, and iconography.</li><li><strong>Limited Customisation:</strong> Children should have minimal to no internal customisation options. Their purpose is to enforce strict consistency.</li><li><strong>Accessibility:</strong> Ensure these basic elements meet accessibility standards (e.g., proper contrast for text, touch target sizes for buttons).</li></ul><p>Simple Code Example,</p><pre>@Composable<br>fun AppText(<br>    text: String,<br>    style: TextStyle = MaterialTheme.typography.bodyMedium,<br>    color: Color = MaterialTheme.colorScheme.onBackground<br>) {<br>    Text(text = text, style = style, color = color)<br>}<br><br>@Composable<br>fun AppButton(<br>    text: String,<br>    onClick: () -&gt; Unit<br>) {<br>    Button(onClick = onClick) {<br>        AppText(text = text, style = MaterialTheme.typography.labelLarge)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXvL35LmmmPKYWf--jZ5CQ.png" /></figure><h4>2. Widget: The Composite Component</h4><p>“Widgets” are combinations of one or more “CHILD” that form a slightly more complex, self-contained UI pattern. They serve a specific purpose and encapsulate common UI structures that appear repeatedly throughout your app.</p><p><strong>Examples of Widgets:</strong></p><ul><li><strong>Product Card:</strong> A combination of an image view, a title text view, a price text view, and potentially an “add to cart” button.</li><li><strong>List Item:</strong> An icon, a main title, a subtitle, and an arrow icon.</li><li><strong>Header Bar:</strong> A title text view, a back button icon, and perhaps an action icon.</li><li><strong>Empty State View:</strong> An icon, a descriptive text view, and a call-to-action button.</li><li><strong>User Profile Header:</strong> An avatar image, a name text view, and a short bio text view.</li></ul><p><strong>Considerations for Widgets:</strong></p><ul><li><strong>Parameterization:</strong> Widgets should accept parameters (e.g., image URL, title string, button text) to make them adaptable to different data, but their internal structure remains consistent.</li><li><strong>Encapsulation:</strong> They should manage their own layout and internal logic, exposing only necessary properties to their parent.</li><li><strong>Semantic Naming:</strong> Give widgets names that describe their purpose (e.g., ProductCard, UserProfileListItem).</li></ul><p>Simple Code Example,</p><pre>@Composable<br>fun ProductCard(<br>    title: String,<br>    description: String,<br>    imageUrl: String,<br>    onClick: () -&gt; Unit<br>) {<br>    Card(<br>        modifier = Modifier<br>            .padding(8.dp)<br>            .clickable { onClick() }<br>    ) {<br>        Column(Modifier.padding(16.dp)) {<br>            AsyncImage(model = imageUrl, contentDescription = title)<br>            Spacer(modifier = Modifier.height(8.dp))<br>            AppText(text = title, style = MaterialTheme.typography.titleMedium)<br>            AppText(text = description, style = MaterialTheme.typography.bodySmall)<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewSp2OUeS-tL8RyNJAinog.png" /></figure><h4>3. Root View: The Screen Layout</h4><p>“Root Views” are the top-level containers that combine multiple “Widgets” and sometimes “Children” to form a complete screen or a significant section of a screen. They represent the unique layout of a particular feature or section of your application.</p><p><strong>Examples of Root Views:</strong></p><ul><li><strong>Product Listing Screen:</strong> A combination of a HeaderBar widget, a grid of ProductCard widgets</li><li><strong>User Profile Screen: S</strong>eries of ListItem widgets for various settings or actions.</li></ul><p><strong>Considerations for Root Views,</strong></p><ul><li><strong>Orchestration:</strong> Root views are responsible for arranging widgets and children into a meaningful layout. They often handle the overall data fetching and state management for the screen.</li><li><strong>Unique Layouts:</strong> While they use reusable components, the specific arrangement of these components defines the unique purpose of the screen.</li><li><strong>Business Logic:</strong> This level often interacts most directly with the app’s business logic, passing data down to its child widgets.</li></ul><p>Simple Code Example,</p><pre>@Composable<br>fun ProductGrid(products: List&lt;Product&gt;, onItemClick: (Product) -&gt; Unit) {<br>    LazyVerticalGrid(columns = GridCells.Fixed(2)) {<br>        items(products) { product -&gt;<br>            ProductCard(<br>                title = product.title,<br>                description = product.description,<br>                imageUrl = product.imageUrl,<br>                onClick = { onItemClick(product) }<br>            )<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGkGdUH5JTQ0pwac5CZEvg.png" /></figure><p>If you’re planning a revamp, don’t just reskin your app. Build a <strong>reusable component strategy</strong>. The investment pays off in maintainability, speed, and user satisfaction.</p><p>💬 What’s your approach to reusable UI components? Drop your strategies in the comments — I’d love to hear them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192205fd90ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Flexible Alert System in a Multi-Module Android Compose App with Factory Pattern]]></title>
            <link>https://medium.com/@ayesh.don/building-a-flexible-alert-system-in-a-multi-module-android-compose-app-with-factory-pattern-b7bd016f7d31?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7bd016f7d31</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 14:58:11 GMT</pubDate>
            <atom:updated>2025-08-20T14:58:11.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saJLG1mjhta4kRS3GvC3hg.png" /></figure><p>When working on large-scale <strong>multi-module Android apps</strong>, it’s common to reuse UI components across multiple features. One such component is the <strong>AlertDialog</strong> used for errors, info messages, warnings, confirmations, and more.</p><p>Instead of creating ad-hoc alerts everywhere, let’s build a <strong>centralised and flexible alert system</strong> in a common-uis module. To achieve this, we’ll leverage the <strong>Factory Pattern</strong>.</p><p>🔹 What is the Factory Pattern in Kotlin?</p><p>At its core, the Factory pattern is a <strong>creational design pattern</strong> that provides a way to create objects without specifying the exact class of object that will be created. It’s all about delegating the responsibility of object creation to a “factory” function or class.</p><p>This helps when:</p><ul><li>You want to <strong>centralise object creation</strong>.</li><li>You want <strong>flexibility to add new types</strong> in the future.</li><li>You want to avoid cluttering your codebase with repeated instantiation logic.</li></ul><p><strong>Example:</strong></p><pre><br>interface Notification {<br>    fun show()<br>}<br><br><br>class ErrorNotification(private val message: String) : Notification {<br>    override fun show() {<br>        println(&quot;Error: $message&quot;)<br>    }<br>}<br><br>class InfoNotification(private val message: String) : Notification {<br>    override fun show() {<br>        println(&quot;Info: $message&quot;)<br>    }<br>}<br><br>class SuccessNotification(private val message: String) : Notification {<br>    override fun show() {<br>        println(&quot;Success: $message&quot;)<br>    }<br>}<br><br>object NotificationFactory {<br>    fun create(type: NotificationType, message: String): Notification {<br>        return when (type) {<br>            NotificationType.ERROR -&gt; ErrorNotification(message)<br>            NotificationType.INFO -&gt; InfoNotification(message)<br>            NotificationType.SUCCESS -&gt; SuccessNotification(message)<br>        }<br>    }<br>}<br><br>enum class NotificationType {<br>    ERROR, INFO, SUCCESS<br>}<br><br>fun main() {<br>    val error = NotificationFactory.create(NotificationType.ERROR, &quot;Something went wrong!&quot;)<br>    val info = NotificationFactory.create(NotificationType.INFO, &quot;This is an info message.&quot;)<br>    val success = NotificationFactory.create(NotificationType.SUCCESS, &quot;Operation completed!&quot;)<br><br>    error.show()<br>    info.show()<br>    success.show()<br>}</pre><p>🔹 Real-World Example: A Common Alert System</p><p>Think of it like a car factory. You don’t need to know the intricate details of how to build a sedan or a truck. You just tell the factory, “I need a sedan,” and it returns a completed car. In our code, this means we can have a single function (AlertFactory) that takes a request (e.g., &quot;I need an error alert&quot;) and returns the correct composable without the caller needing to know the specific implementation details of ErrorAlertView or InfoAlertView.</p><p>This pattern offers two main benefits for our use case:</p><ol><li><strong>Decoupling:</strong> The code that <em>uses</em> the alert is decoupled from the code that <em>creates</em> the alert. This makes your feature modules much cleaner.</li><li><strong>Flexibility:</strong> You can easily add new types of alerts in the future (like a WarningAlert) by simply adding a new case to the factory, without having to change any of the existing consuming code.</li></ol><p>Let’s apply this pattern to our alert dialog problem. We’ll create a common-uis module with a dedicated AppDialog composable that acts as our public-facing API. All the logic for which alert to show is handled internally by our factory.</p><p>First, we define our different alert types using a sealed class. This is a perfect fit because we have a finite set of known alert types.</p><pre>sealed class AlertType {<br>    data class ErrorAlert(<br>        val title: String,<br>        val message: String,<br>    ) : AlertType()<br><br>    data class InfoAlert(<br>        val title: String,<br>        val message: String,<br>    ) : AlertType()<br><br>    data class WarningAlert(<br>        val title: String,<br>        val message: String,<br>    ) : AlertType()<br>}</pre><p>Next, we create the individual composable functions for each alert type. These are the specific UI implementations that our factory will use.</p><pre>@Composable<br>fun ErrorAlertView(<br>    title: String,<br>    message: String,<br>    onDismissRequest: () -&gt; Unit,<br>) {<br>    AlertDialog(<br>        onDismissRequest = onDismissRequest,<br>        title = { Text(title) },<br>        text = { Text(message) },<br>        confirmButton = {<br>            TextButton(onClick = onDismissRequest) {<br>                Text(&quot;OK&quot;)<br>            }<br>        },<br>    )<br>}<br><br>@Composable<br>fun InfoAlertView(<br>    title: String,<br>    message: String,<br>    onDismissRequest: () -&gt; Unit,<br>) {<br>    AlertDialog(<br>        onDismissRequest = onDismissRequest,<br>        title = { Text(title) },<br>        text = { Text(message) },<br>        confirmButton = {<br>            TextButton(onClick = onDismissRequest) {<br>                Text(&quot;OK&quot;)<br>            }<br>        },<br>    )<br>}</pre><p>Now for the star of the show: our <strong>AlertFactory</strong>. This function takes an AlertType and, using a when expression, returns the correct alert composable.</p><pre>@Composable<br>fun AlertFactory(<br>    alertType: AlertType,<br>    onDismissRequest: () -&gt; Unit,<br>) {<br>    when (alertType) {<br>        is AlertType.ErrorAlert -&gt; {<br>            ErrorAlertView(<br>                onDismissRequest = onDismissRequest,<br>                title = alertType.title,<br>                message = alertType.message,<br>            )<br>        }<br><br>        is AlertType.InfoAlert -&gt; {<br>            InfoAlertView(<br>                onDismissRequest = onDismissRequest,<br>                title = alertType.title,<br>                message = alertType.message,<br>            )<br>        }<br><br>        is AlertType.WarningAlert -&gt; {<br>            // this one for future enhancement. To practice you can build alert for this<br>            throw IllegalArgumentException(&quot;WarningAlert is not implemented yet&quot;)<br>        }<br>    }<br>}</pre><p>Finally, we wrap our factory in a simple, exposed composable that all other modules will use. This is the only function they need to know about.</p><pre>@Composable<br>fun AppDialog(<br>    alertType: AlertType,<br>    onDismissRequest: () -&gt; Unit,<br>) {<br>    AlertFactory(<br>        alertType = alertType,<br>        onDismissRequest = onDismissRequest,<br>    )<br>}</pre><p>To use this from any other module (like a login screen in a login module), it&#39;s as simple as calling AppDialog and passing the appropriate AlertType. The rest of the logic is taken care of for you.</p><pre>// In a feature module (e.g., main-screen)<br>@Composable<br>fun MainScreen() {<br>    val showLoginErrorAlert = remember { mutableStateOf(false) }<br><br>    // ... your screen content<br>    Button(onClick = { showLoginErrorAlert.value = true }) {<br>        Text(&quot;Show Alert&quot;)<br>    }<br><br>    if (showLoginErrorAlert.value) {<br>        AppDialog(<br>            alertType =<br>                AlertType.InfoAlert(<br>                    title = &quot;Login Successful!&quot;,<br>                    message = &quot;You have been logged in successfully.&quot;,<br>                ),<br>            onDismissRequest = {<br>                showLoginErrorAlert.value = false<br>            },<br>        )<br>    }<br>}</pre><p>By leveraging the Factory pattern, we’ve created a centralized and scalable system for handling alerts. We’ve separated the alert creation logic from the UI presentation logic, making our code more modular, reusable, and easy to maintain. When a new alert type is needed, all we have to do is update our common-uis module, and no other feature modules will be impacted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7bd016f7d31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Android Developer’s Guide to Bulletproof API Calls]]></title>
            <link>https://medium.com/@ayesh.don/the-android-developers-guide-to-bulletproof-api-calls-1181c6910dfa?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1181c6910dfa</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 03:57:55 GMT</pubDate>
            <atom:updated>2025-08-14T03:57:55.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qic5wDKhfMp2STQ0041K-w.png" /><figcaption>Mastering API Calls in Android with Retrofit, The safeApiCall Best Practice</figcaption></figure><p>Making API calls is a fundamental part of most modern Android applications. But handling network requests reliably, especially when things go wrong, can be a headache. You need to consider network errors, server-side failures, and unexpected responses. This is where a robust and reusable solution comes in.</p><p>In this blog post, we’ll dive into a powerful and clean approach to handling your API calls using <strong>Kotlin Coroutines</strong> and <strong>Retrofit</strong>. The solution we’ll explore uses a generic safeApiCall method that encapsulates the logic for success, failure, and error handling, making your API code clean, safe, and easy to maintain.</p><h4>Why You Need a Safe API Call Wrapper</h4><p>Without a structured approach, your API calls can quickly become messy. A typical call might look something like this</p><pre>try {<br>    val response = someApiService.getUserProfile()<br>    if (response.isSuccessful) {<br>        val user = response.body()<br>        // Handle success<br>    } else {<br>        // Handle API error<br>    }<br>} catch (e: Exception) {<br>    // Handle network error<br>}</pre><p>Looks simple, right? But in a real-world app:</p><ul><li>You repeat if (response.isSuccessful) in every API call.</li><li>Error body parsing becomes copy-paste hell.</li><li>Exceptions from network issues aren’t consistently handled.</li></ul><p>This leads to <strong>inconsistent error handling</strong>, <strong>more bugs</strong>, and <strong>harder debugging</strong>.</p><p>That’s where <strong>safeApiCall</strong> comes in. This solution revolves around two key components, a sealed class to represent the state of our network request, and a generic function to execute the API call safely.</p><p><strong>The </strong>NetworkResult<strong> Sealed Class</strong></p><p>This define a sealed class to represent the three possible outcomes of an API call: <strong>Success</strong>, <strong>Error</strong>, or <strong><em>Loading(Optional)</em></strong>. This is a great way to handle state in a type-safe manner.</p><pre>sealed class NetworkResult&lt;out T : Any&gt; {<br>    data class Success&lt;out T : Any&gt;(val data: T) : NetworkResult&lt;T&gt;()<br>    data class Error(val apiError: ApiError) : NetworkResult&lt;Nothing&gt;()<br>    object Loading : NetworkResult&lt;Nothing&gt;()<br>}<br><br>data class ApiError(<br>    val message: String? = null,<br>    val code: Int? = null<br>)</pre><p><em>By using a sealed class, we can ensure that our UI or business logic handles every possible state without missing one.</em></p><p><strong>The </strong>safeApiCall<strong> Function</strong></p><pre>suspend fun &lt;T : Any&gt; safeApiCall(<br>    apiCall: suspend () -&gt; Response&lt;T&gt;<br>): NetworkResult&lt;T&gt; =<br>    try {<br>        apiCall().run {<br>            when {<br>                isSuccessful -&gt; {<br>                    body()?.let {<br>                        NetworkResult.Success(it)<br>                    } ?: NetworkResult.Error(<br>                        ApiError(<br>                            message = &quot;Response body is null&quot;,<br>                        ),<br>                    )<br>                }<br>                else -&gt; NetworkResult.Error(parseApiError())<br>            }<br>        }<br>    } catch (e: Exception) {<br>        NetworkResult.Error(<br>            ApiError(<br>                message = e.localizedMessage ?: &quot;Unknown error&quot;,<br>            ),<br>        )<br>    }<br></pre><pre>private fun &lt;T&gt; Response&lt;T&gt;.parseApiError(): ApiError {<br>    val errorBody = errorBody()?.string()<br>    return try {<br>        Gson().fromJson(errorBody, ApiErrorRoot::class.java).error?.get(0)<br>            ?: ApiError(message = &quot;Unknown error&quot;)<br>    } catch (e: Exception) {<br>        ApiError(message = &quot;Failed to parse error body&quot;)<br>    }<br>}</pre><p>This is the core of solution. The safeApiCall function is a generic suspend function that takes another suspend function (apiCall) as a parameter. It&#39;s responsible for executing the API call, handling both success and error scenarios, and wrapping the result in our NetworkResult sealed class.<br><strong>try-catch block</strong> is the first line of defence. It catches low-level exceptions like network connectivity issues (IOException) or timeouts, which are not handled by Retrofit&#39;s isSuccessful flag. <strong>apiCall().run</strong>executes the actual Retrofit network request.</p><p><strong>when { isSuccessful -&gt; ... }</strong> <br><em>If the server responds with a 2xx HTTP status code, we check the response body.</em></p><p><strong>else -&gt; NetworkResult.Error(parseApiError()</strong></p><p><em>If the response is not successful (e.g., 4xx or 5xx status codes), we call a helper function </em><em>parseApiError() to extract the specific error message from the response body.</em></p><p>Now, let’s see how clean our API service becomes. Instead of try-catch blocks everywhere, your ViewModel or repository will call a single function.</p><pre>class UserRepository(private val apiService: ApiService) {<br><br>    suspend fun getUserProfile(): NetworkResult&lt;User&gt; {<br>        return safeApiCall { apiService.getUserProfile() }<br>    }<br>    <br>    suspend fun updateUserProfile(user: User): NetworkResult&lt;User&gt; {<br>        return safeApiCall { apiService.updateUserProfile(user) }<br>    }<br>}</pre><h3>Benefits of This Approach</h3><ul><li><strong>Consistent</strong> error handling across all API calls.</li><li><strong>No more boilerplate</strong> success/error checks.</li><li><strong>Centralized</strong> error parsing logic.</li><li><strong>Easier debugging</strong> because all network responses pass through one place.</li></ul><p>Give this pattern a try in your next Android project. Your future self will thank you! Happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1181c6910dfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Hooks :Enforcing Code Quality and Naming Conventions in Android Projects with Git Hooks]]></title>
            <link>https://medium.com/@ayesh.don/git-hooks-enforcing-code-quality-and-naming-conventions-in-android-projects-with-git-hooks-60307c1d066c?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/60307c1d066c</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 03:17:00 GMT</pubDate>
            <atom:updated>2025-08-08T03:17:00.748Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Git Hooks</strong> :Enforcing Code Quality and Naming Conventions in Android Projects with Git Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ba--wYDClbi1U5R953uDOg.png" /></figure><p>As an Android developer, maintaining a clean and consistent codebase is essential for the long term success of any project. It’s not just about writing quality code. It also involves adhering to team standards for commit messages, branch naming, and code formatting. While code reviews play a vital role, it’s far more efficient to catch these issues <em>before</em> they make it to a pull request.</p><p>That’s where Git hooks come into play. Git hooks , stored in the .git/hooks directory of your local repository are scripts that execute automatically at various stages of the Git workflow. By using them, we can enforce team conventions right on the developer’s machine, stopping poorly formatted code and inconsistent practices before they ever leave the local repo.</p><p>In this blog post, we’ll dive into three essential Git hooks for Android development</p><ul><li>commit-msg: To validate your commit message format.</li><li>pre-commit: To run code quality checks like linting before a commit.</li><li>pre-push: To ensure your branch name follows team conventions before pushing.</li></ul><p>By the end of this article, you’ll have practical examples and a clear understanding of how to implement these hooks in your own Android project</p><h4><strong>1. Why Git Hooks? The Android Development Pain Points</strong></h4><p>Before diving into the “how,” let’s take a moment to understand the “why.” Consider some common pain points in Android development teams,</p><ol><li><strong>Unclear Commit Messages:</strong> Ever come across commits labeled simply as “fix” or “update”? Without context, it’s nearly impossible to understand what was changed, making it difficult to track progress or generate meaningful release notes.</li><li><strong>Inconsistent Branch Naming:</strong> One developer uses feature/JIRA-123, another goes with jira_123_feature, and someone else just writes jira_123. These inconsistencies create confusion and make branch management unnecessarily messy.</li><li><strong>Unformatted Code Slipping Through:</strong> Sometimes developers forget to run tools like ktlint or detekt before committing. This results in inconsistent code formatting that clutters diffs and adds friction to the code review process.</li></ol><p>Git hooks provide an automated solution to these problems, acting as a gatekeeper for your repository.</p><h4>2. Enforcing Commit Message Format with commit-msg</h4><p>The commit-msg hook is triggered after a commit message is entered but before the commit is created. This hook validates the commit message against a predefined pattern, such as the Conventional Commits specification.</p><pre>#!/bin/sh<br><br># Get the path to the commit message file<br>COMMIT_MSG_FILE=$1<br><br># Define the regex pattern for the commit message<br>PATTERN=&quot;^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?:.+&quot;<br><br># Read the first line of the commit message<br>COMMIT_MESSAGE=$(head -n1 &quot;$COMMIT_MSG_FILE&quot;)<br><br># Check if the commit message matches the pattern<br>if ! [[ &quot;$COMMIT_MESSAGE&quot; =~ $PATTERN ]]; then<br>  echo &quot;❌❌❌Invalid commit message format. Please follow the convention:❌❌&quot; &gt;&amp;2<br>  echo &quot;e.g. &#39;feat(scope): a short description&#39;&quot; &gt;&amp;2<br>  echo &quot;Available types: feat, fix, docs, style, refactor, test, chore&quot; &gt;&amp;2<br>  exit 1<br>fi<br><br>exit 0</pre><p>This script checks if the first line of the commit message follows a specific format (e.g., type(scope): description). If the message doesn&#39;t match the pattern, the script outputs an error and <strong>prevents the commit</strong>. This practice makes the project&#39;s commit history more readable and useful for understanding the purpose of each commit at a glance.</p><h4>3. Automating Code Formatting with pre-commit</h4><p>The pre-commit hook runs just before a commit is finalized. It&#39;s the perfect place to run <strong>ktlint</strong> or other code style checks. This ensures that every commit is free of style violations, keeping the codebase tidy.</p><pre>#!/bin/sh<br><br># Running ktlint pre-commit check...<br>echo &quot;Running ktlint pre-commit check...&quot;<br><br># Use the Gradle wrapper to run ktlintCheck<br>./gradlew ktlintCheck<br><br># Store the exit status of the previous command<br>ktlint_status=$?<br><br># If ktlintCheck failed, exit with an error<br>if [ $ktlint_status -ne 0 ]; then<br>  echo &quot;ktlint check failed! Please fix the code style issues before committing.&quot;<br>  exit 1<br>fi<br><br># If ktlintCheck passed, allow the commit to proceed<br>echo &quot;ktlint check passed. Committing changes.&quot;<br>exit 0</pre><p>This script runs the ktlintCheck Gradle task. If the linter finds any style violations, the script will exit with a non-zero status, <strong>aborting the commit</strong>. This forces the developer to fix the issues before they can commit the code. This is an excellent way to maintain a clean and consistent code style across the entire team.</p><h4>4.The pre-push Hook: Running Tests and Validating Branch Names</h4><p>The pre-push hook runs right before git push. It&#39;s the last line of defense for a developer&#39;s local changes. This is the ideal place to run a full suite of unit tests to ensure that the code is working as expected before it&#39;s shared with the team. It can also be used to enforce branch naming conventions.</p><pre>#!/bin/sh<br><br>echo &quot;Running pre-push hook...&quot;<br><br># Get the current branch name<br>branch_name=$(git rev-parse --abbrev-ref HEAD)<br><br># Define the regex pattern for the branch name<br>pattern=&quot;^(feature|bugfix|chore|test)/.+&quot;<br><br># Check if the branch name matches the pattern<br>if ! [[ $branch_name =~ $pattern ]]; then<br>  echo &quot;Error: Invalid branch name.&quot;<br>  echo &quot;Branch names must follow the format &lt;tag-name&gt;/&lt;description&gt;.&quot;<br>  echo &quot;Allowed tags: feature, bugfix, chore, test.&quot;<br>  exit 1<br>fi<br><br>echo &quot;Branch name check passed.&quot;<br><br># Run Android unit tests using Gradle<br>echo &quot;Running unit tests...&quot;<br>./gradlew test<br><br># Check the exit status of the test command<br>if [ $? -ne 0 ]; then<br>  echo &quot;Error: Unit tests failed.&quot;<br>  exit 1<br>fi<br><br>echo &quot;Unit tests passed.&quot;<br>echo &quot;Pre-push hook finished successfully.&quot;<br><br>exit 0</pre><p>This script performs two critical checks:</p><ol><li><strong>Branch Name Validation</strong>: It ensures that the branch name conforms to a team-wide standard (e.g., feature/my-new-feature). This helps in automating CI/CD pipelines and maintaining a clean branch history.</li><li><strong>Unit Test Execution</strong>: It runs all unit tests by executing ./gradlew test. If any test fails, the push is <strong>aborted</strong>, preventing potentially broken code from being pushed to the remote repository. This saves a lot of time and effort in debugging issues that could have been caught locally.</li></ol><h4>5. The .githooks Directory</h4><p>By default, Git hooks live in the .git/hooks/ directory, which is part of the repository but not committed to it. This means every developer has to set up these hooks manually, which is not ideal.</p><p>A better approach is to store the hooks in a separate directory in your project’s root, like .githooks/, and tell Git to use it. This way, the hooks are version-controlled and shared with the entire team.</p><p>Steps :</p><pre>mkdir .githooks</pre><p>Then, configure Git to use this new directory. Add the following to your git config (this is a one-time setup for the project):</p><pre>git config core.hooksPath .githooks</pre><p>Or for android developer can create custom gradle task to copy the file to root dir.</p><p>Git hooks are a simple yet powerful way to <strong>enforce best practices</strong> and <strong>automate quality checks</strong> in Android development. By integrating pre-commit, commit-msg, and pre-push hooks into your workflow, you can ensure a cleaner codebase, more meaningful commit history, and a more stable main branch. It&#39;s an investment that pays off by reducing bugs and improving overall team efficiency. Give them a try on your next project! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60307c1d066c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modularizing Hilt for Clean Architecture]]></title>
            <link>https://medium.com/@ayesh.don/modularizing-hilt-for-clean-architecture-4e990f1eb0b6?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e990f1eb0b6</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 04:09:41 GMT</pubDate>
            <atom:updated>2025-07-21T04:10:55.644Z</atom:updated>
            <content:encoded><![CDATA[<p>As Android applications grow, managing dependencies can quickly become a tangled mess. A common scenario involves a single, monolithic Hilt AppModule that provides everything from network clients to repositories and use cases. While functional, this approach often leads to a module that&#39;s difficult to read, maintain, and scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbHMzHI0vcQYqb_BanV1ww.png" /></figure><p>If your AppModule looks like a never-ending list of @Provides methods, it&#39;s time for a refactor! In this post, we&#39;ll explore why and how to separate your Hilt modules, specifically focusing on moving Repositories and Use Cases into their own dedicated modules.</p><h4>Why Separate Hilt Modules?</h4><p>The idea of breaking down a large module isn’t just about aesthetics. it brings significant architectural benefits</p><ul><li><strong>Single Responsibility Principle (SRP):</strong> Each module should have one reason to change. A RepositoriesModule only changes when repository implementations change. A UseCasesModule only changes when business logic use cases are added or modified. This makes your codebase more predictable.</li><li><strong>Improved Readability and Discoverability:</strong> When a module is focused, it’s much easier for you or another developer to understand its purpose and find specific dependency provisions. No more endless scrolling through a single AppModule!</li><li><strong>Enhanced Maintainability:</strong> Debugging and making changes become simpler. If there’s an issue with a use case, you know exactly which module to check. This reduces the cognitive load and potential for introducing new bugs.</li><li><strong>Better Testability:</strong> With clearer separation, you can more easily provide mock implementations for specific layers during testing. For instance, in a UI test, you might only need to mock your use cases, not your entire application’s dependencies.</li><li><strong>Optimized Build Times (Minor):</strong> While not the primary driver for small projects, Hilt’s annotation processor can sometimes benefit from smaller, more focused modules, potentially leading to slightly faster incremental builds in larger codebases.</li></ul><h4>Dedicated Modules</h4><p>We’ll refactor this into three distinct modules:</p><ol><li><strong>AppModule</strong>: For core application-wide dependencies (e.g., Firebase instances,Retrofit,RoomDB, etc).</li><li><strong>RepositoriesModule</strong>: For providing all your repository interface implementations.</li><li><strong>UseCasesModule</strong>: For providing all your domain layer use cases.</li></ol><p><strong>Create </strong><strong>RepositoriesModule</strong></p><p>This module will be responsible solely for providing instances of your repository interfaces. It depends on data sources, which can be provided in AppModule or a dedicated DataSourcesModule if your app warrants it.</p><pre><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object RepositoriesModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideAuthRepository(authDataSource: FirebaseAuthDataSource): AuthRepository {<br>        return AuthRepositoryImpl(authDataSource)<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideUserRepository(firestore: FirebaseFirestore): UserRepository {<br>        return UserRepositoryImpl(firestore)<br>    }<br>}</pre><p><strong>Create </strong><strong>UseCasesModule</strong></p><p>This module will contain all your business logic use cases. Notice that Hilt automatically handles injecting dependencies like UserRepository or AuthTokenPrefDelegate into these use cases, as long as those dependencies are also provided by other Hilt modules installed in the same component (SingletonComponent in this case).</p><pre><br>@Module<br>@InstallIn(SingletonComponent::class)<br>object UseCasesModule {<br><br><br>    @Provides<br>    @Singleton<br>    fun provideAuthTokenUseCases(tokenDelegate: AuthTokenPrefDelegate): AuthTokenUseCase {<br>        return AuthTokenUseCase(<br>            readAuthToken = ReadAuthTokenUseCase(tokenDelegate),<br>            saveAuthToken = SaveAuthTokenUseCase(tokenDelegate),<br>        )<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideAppCheckHandelUseCase(<br>        repository: UserRepository, // Injected from RepositoriesModule<br>        tokenDelegate: AuthTokenPrefDelegate,// Injected from AppModule<br>        saveProfileDataUseCase: SaveProfileDataUseCase,<br>    ): CheckAndHandleUserLoginUseCase {<br>        return CheckAndHandleUserLoginUseCase(<br>            repository,<br>            SaveProfileCompleteUseCase(tokenDelegate),<br>            saveProfileDataUseCase,<br>        )<br>    }<br>    // ... other use case providers<br>}</pre><p><strong>Refactor </strong><strong>AppModule<br></strong>Finally, your AppModule becomes lean and focused on core, application-wide utilities.</p><pre>// com.happymesport.merchant.di.AppModule.kt<br>@Module<br>@InstallIn(SingletonComponent::class)<br>object AppModule {<br><br>    @Provides<br>    @Singleton<br>    fun provideFirebaseAuth(): FirebaseAuth {<br>        return FirebaseAuth.getInstance()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideFirebaseFireStore(): FirebaseFirestore {<br>        return FirebaseFirestore.getInstance()<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideFirebaseAuthDataSource(firebaseAuth: FirebaseAuth): FirebaseAuthDataSource {<br>        return FirebaseAuthDataSource(firebaseAuth)<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideAuthCodePrefDelegate(application: Application): AuthTokenPrefDelegate {<br>        return AuthTokenPrefDelegateImpl(context = application)<br>    }<br><br>    @Provides<br>    @Singleton<br>    fun provideUserProfilePrefDelegate(application: Application): UserDataPrefDelegate {<br>        return UserDataPrefDelegateImpl(context = application)<br>    }<br>}</pre><p>By taking the time to separate your Hilt @Modules, you&#39;re not just reorganizing code. you&#39;re actively improving the architectural health of your Android application. This practice leads to a cleaner, more understandable, and ultimately more scalable codebase that will be a joy to work with, both for you and your future teammates. Embrace modularity, and watch your Android project flourish!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e990f1eb0b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-QA Verification Process in Mobile App Development: Closing the Gap Between Dev and QA]]></title>
            <link>https://medium.com/@ayesh.don/pre-qa-verification-process-in-mobile-app-development-closing-the-gap-between-dev-and-qa-0612d4269afd?source=rss-dcfee1f4aef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0612d4269afd</guid>
            <category><![CDATA[qa-testing]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[good-practices]]></category>
            <dc:creator><![CDATA[Ayesh Don]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 03:50:55 GMT</pubDate>
            <atom:updated>2025-06-30T03:50:55.972Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve just finished a new feature for the mobile app. The code is clean, the animations are smooth, and it works flawlessly on your emulator. You mark the ticket as “Done” and hand it over to the QA team, ready to move on to the next task. But then, a few hours later, a bug report lands in your inbox: “This isn’t working as expected.”</p><p>The cycle of “it works on my machine” and “it’s a bug” is a familiar one in software development, and it often stems from a simple yet critical issue: <strong>a mismatch in understanding the requirements.</strong> This can lead to frustration, wasted time, and delays in releasing a high-quality product.</p><p>So, how can we, as mobile developers, ensure our features are truly “QA Ready” and not just “Dev Complete”? The key is proactive collaboration and a little bit of foresight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvIE26HFF1a41QjbuCpsBQ.png" /><figcaption><strong><em>To streamline the process and reduce friction, introducing a Pre-QA Verification Session can be a game-changer.</em></strong></figcaption></figure><h3>A Pre-QA Verification Session</h3><p>Before handing off any new feature to the QA team, organize a short <strong>Pre-QA Verification</strong> session that includes:</p><ul><li><strong>QA Engineer</strong>: <em>Reviews and refines test cases, raises immediate concerns or gaps</em></li><li><strong>Developer(Mobile and backend)</strong> : <em>Walks through the implemented feature and shares any edge-case considerations</em></li><li><strong>Product Owner or Business Analyst (optional but helpful)<em> : </em></strong><em>Joins if business logic or requirement clarifications are needed.</em></li></ul><h3>🎯 Goal:</h3><blockquote>Ensure everyone shares the same understanding of the requirements, test scenarios, edge cases, and success criteria — <em>before</em> formal QA begins.</blockquote><p>What Happens During the Session?</p><p><strong>1.Live Demo by Developer</strong></p><p>The developer walks through the newly completed feature in the dev/staging environment showcasing,</p><ul><li>User flow</li><li>Edge cases handled</li><li>Error states</li><li>Backend/API integrations</li></ul><p><strong>2. QA Test Case Review</strong></p><p>The QA team shares their planned test cases (e.g., in <strong>TestRail</strong>, <strong>Zephyr</strong>, or another test management tool). The group confirms,</p><ul><li>Are all scenarios covered?</li><li>Are negative and boundary cases included?</li><li>Are test data and environments aligned?</li></ul><p><strong>3. Mocking/Proxy Setup (If Needed)</strong></p><p>If API integration is involved, QA can simulate or inspect API responses using tools like <a href="https://mitmproxy.org/">mitmproxy</a></p><p><strong>4.Clarifications &amp; Adjustments</strong></p><p>Any ambiguity in the requirements is clarified right then and there reducing later delays or rejected tickets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtY8oSCiWfItG4gHDHGmdQ.png" /></figure><h4>Benefits of Pre-QA Verification</h4><ul><li>Fewer misunderstandings between Dev and QA</li><li>Reduced bug reopen rates due to requirement gaps</li><li>Improved test coverage</li><li>Faster QA cycles</li><li>Better collaboration and shared ownership of quality</li></ul><p>By taking these extra steps, you’re not just sending a feature to QA; you’re sending a feature that’s been thoroughly vetted and is ready for a focused, efficient testing cycle. This shift from a siloed handoff to a collaborative partnership will lead to a smoother development process, fewer bugs, and a better product for your users.</p><p><strong>What’s your favourite tip for a smooth dev-to-QA handoff? Share it in the comments! :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0612d4269afd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>