<?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 Gaurav Bajaj on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Bajaj on Medium]]></description>
        <link>https://medium.com/@gauravbajaj?source=rss-e08f1b8fda3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*26e5pyGXQFUPsorU.jpg</url>
            <title>Stories by Gaurav Bajaj on Medium</title>
            <link>https://medium.com/@gauravbajaj?source=rss-e08f1b8fda3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:35:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravbajaj/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Clean Login Screen in Android with Jetpack Compose]]></title>
            <link>https://medium.com/@gauravbajaj/building-a-clean-login-screen-in-android-with-jetpack-compose-053824d05c01?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/053824d05c01</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 00:26:33 GMT</pubDate>
            <atom:updated>2025-10-15T00:26:33.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onp2CRXj5xdtfTtf1Vr7tQ.png" /></figure><p>Login screens are the gateway to most mobile applications. They’re often the first interaction users have with your app, so making them clean, functional, and user-friendly is crucial. In this tutorial, I’ll show you how to build a simple yet elegant login screen using Jetpack Compose and Material Design 3.</p><h3>What We’re Building</h3><p>We’ll create a login screen with:</p><ul><li>Email input field</li><li>Password input field (with masked text)</li><li>A submit button</li><li>Clean, centered layout with proper spacing</li></ul><h3>Prerequisites</h3><p>Before we start, make sure you have:</p><ul><li>Android Studio (latest version recommended)</li><li>Basic knowledge of Kotlin</li><li>Jetpack Compose dependencies set up in your project</li></ul><h3>Setting Up Dependencies</h3><p>First, ensure your build.gradle.kts file includes the necessary Compose dependencies:</p><pre>dependencies {<br>    implementation(&quot;androidx.compose.material3:material3:1.1.2&quot;)<br>    implementation(&quot;androidx.activity:activity-compose:1.8.0&quot;)<br>    implementation(&quot;androidx.compose.ui:ui:1.5.0&quot;)<br>}</pre><h3>Building the Login Screen</h3><p>Let’s break down the implementation step by step.</p><h3>Step 1: Create the Main Activity</h3><p>Start by creating your MainActivity that sets up the Compose UI:</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MaterialTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    LoginScreen()<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Step 2: Create the Login Screen Composable</h3><p>The heart of our login screen is the LoginScreen composable. We&#39;ll use state management to track user input:</p><pre>@Composable<br>fun LoginScreen() {<br>    var email by remember { mutableStateOf(&quot;&quot;) }<br>    var password by remember { mutableStateOf(&quot;&quot;) }<br>    <br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .padding(24.dp),<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        // UI components go here<br>    }<br>}</pre><h3>Step 3: Add the Title</h3><p>A welcoming title sets the tone for your login screen:</p><pre>Text(<br>    text = &quot;Welcome Back&quot;,<br>    fontSize = 28.sp,<br>    style = MaterialTheme.typography.headlineMedium,<br>    modifier = Modifier.padding(bottom = 32.dp)<br>)</pre><h3>Step 4: Implement Input Fields</h3><p>The OutlinedTextField component from Material 3 provides a clean, modern look:</p><pre>OutlinedTextField(<br>    value = email,<br>    onValueChange = { email = it },<br>    label = { Text(&quot;Email&quot;) },<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(bottom = 16.dp),<br>    singleLine = true<br>)</pre><pre>OutlinedTextField(<br>    value = password,<br>    onValueChange = { password = it },<br>    label = { Text(&quot;Password&quot;) },<br>    visualTransformation = PasswordVisualTransformation(),<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(bottom = 24.dp),<br>    singleLine = true<br>)</pre><p>The PasswordVisualTransformation() automatically masks the password input, showing dots instead of characters.</p><h3>Step 5: Add the Submit Button</h3><p>Finally, add a full-width button for submission:</p><pre>Button(<br>    onClick = {<br>        // Handle login logic here<br>        println(&quot;Email: $email&quot;)<br>        println(&quot;Password: $password&quot;)<br>    },<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .height(50.dp)<br>) {<br>    Text(text = &quot;Submit&quot;, fontSize = 16.sp)<br>}</pre><h3>Understanding Key Concepts</h3><h3>State Management with remember and mutableStateOf</h3><p>In Compose, UI state is managed using remember and mutableStateOf. When the state changes, Compose automatically recomposes the affected parts of the UI:</p><pre>var email by remember { mutableStateOf(&quot;&quot;) }</pre><p>This creates a remembered mutable state that persists across recompositions.</p><h3>Layout with Column</h3><p>The Column composable arranges its children vertically. We use:</p><ul><li>horizontalAlignment = Alignment.CenterHorizontally to center items horizontally</li><li>verticalArrangement = Arrangement.Center to center items vertically in the screen</li></ul><h3>Modifiers</h3><p>Modifiers in Compose are powerful tools for styling and behavior:</p><ul><li>.fillMaxSize() makes the component take up all available space</li><li>.padding() adds spacing around components</li><li>.fillMaxWidth() makes the component span the full width</li></ul><h3>Next Steps and Enhancements</h3><p>This basic login screen is a great starting point, but you can enhance it further:</p><ol><li><strong>Add Input Validation</strong>: Check for valid email format and password requirements</li><li><strong>Error Handling</strong>: Display error messages for invalid inputs</li><li><strong>Loading State</strong>: Show a progress indicator during authentication</li><li><strong>Remember Me</strong>: Add a checkbox for persistent login</li><li><strong>Forgot Password</strong>: Include a link for password recovery</li><li><strong>API Integration</strong>: Connect to your backend authentication service</li><li><strong>Navigation</strong>: Navigate to the home screen after successful login</li></ol><h3>Example Enhancement: Input Validation</h3><p>Here’s a quick example of adding basic validation:</p><pre>var emailError by remember { mutableStateOf(false) }</pre><pre>OutlinedTextField(<br>    value = email,<br>    onValueChange = { <br>        email = it<br>        emailError = !android.util.Patterns.EMAIL_ADDRESS.matcher(it).matches()<br>    },<br>    label = { Text(&quot;Email&quot;) },<br>    isError = emailError,<br>    supportingText = {<br>        if (emailError) {<br>            Text(&quot;Please enter a valid email&quot;)<br>        }<br>    }<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_njroMEDZR_voX8IBU_uIQ.png" /></figure><h3>Conclusion</h3><p>Building a login screen with Jetpack Compose is straightforward and results in clean, maintainable code. The declarative nature of Compose makes it easy to reason about your UI and update it as needed.</p><p>The combination of Material Design 3 components and Compose’s powerful state management creates a smooth, modern user experience. As you continue developing your app, this foundation can be extended with additional features like biometric authentication, social login, and more.</p><p>Happy coding! Feel free to customize this login screen to match your app’s branding and requirements.</p><p><em>Have questions or suggestions? Leave a comment below, and let’s discuss Android development!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=053824d05c01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Clean DataStore Wrapper for Android with Hilt]]></title>
            <link>https://medium.com/@gauravbajaj/building-a-clean-datastore-wrapper-for-android-with-hilt-6bfd1a1ca222?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bfd1a1ca222</guid>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 00:03:01 GMT</pubDate>
            <atom:updated>2025-10-15T00:03:01.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DzyOXtzFhKe2-r4SAd7nA.png" /></figure><p>When building Android applications, managing persistent data is a fundamental requirement. While Android offers several options for local data storage, SharedPreferences remains a popular choice for storing small amounts of key-value data, such as user preferences, authentication tokens, and app settings.</p><p>In this article, we’ll explore how to create a clean, reusable DataStore wrapper around SharedPreferences using Dagger Hilt for dependency injection.</p><h3>Why Wrap SharedPreferences?</h3><p>Before diving into the implementation, let’s understand why creating a wrapper class is beneficial:</p><ul><li><strong>Centralized Logic</strong>: All SharedPreferences operations are handled in one place</li><li><strong>Type Safety</strong>: We can add type-specific methods to reduce casting errors</li><li><strong>Testability</strong>: Easier to mock for unit testing</li><li><strong>Dependency Injection</strong>: Seamless integration with Hilt/Dagger</li><li><strong>Maintainability</strong>: Changes to storage logic only need to happen in one place</li></ul><h3>Setting Up Dependencies</h3><p>First, ensure you have Hilt dependencies in your build.gradle file:</p><pre>dependencies {<br>    implementation &quot;com.google.dagger:hilt-android:2.48&quot;<br>    kapt &quot;com.google.dagger:hilt-compiler:2.48&quot;<br>}</pre><h3>The DataStore Implementation</h3><p>Here’s our complete DataStore class:</p><pre>import android.content.Context<br>import android.content.SharedPreferences<br>import dagger.hilt.android.qualifiers.ApplicationContext<br>import javax.inject.Inject<br>import javax.inject.Singleton</pre><pre>@Singleton<br>class DataStore @Inject constructor(@ApplicationContext val context: Context) {<br>    private val sharedPref: SharedPreferences = <br>        context.getSharedPreferences(&quot;AuthFile&quot;, Context.MODE_PRIVATE)</pre><pre>    fun getValue(key: String, defaultValue: String = &quot;&quot;): String {<br>        return sharedPref.getString(key, defaultValue) ?: defaultValue<br>    }</pre><pre>    fun putValue(key: String, value: String) {<br>        sharedPref.edit().putString(key, value).apply()<br>    }</pre><pre>    fun remove(key: String) {<br>        sharedPref.edit().remove(key).apply()<br>    }</pre><pre>    fun clear() {<br>        sharedPref.edit().clear().apply()<br>    }</pre><pre>    fun contains(key: String): Boolean {<br>        return sharedPref.contains(key)<br>    }</pre><pre>    // Support for other data types<br>    fun getInt(key: String, defaultValue: Int = 0): Int {<br>        return sharedPref.getInt(key, defaultValue)<br>    }</pre><pre>    fun putInt(key: String, value: Int) {<br>        sharedPref.edit().putInt(key, value).apply()<br>    }</pre><pre>    fun getBoolean(key: String, defaultValue: Boolean = false): Boolean {<br>        return sharedPref.getBoolean(key, defaultValue)<br>    }</pre><pre>    fun putBoolean(key: String, value: Boolean) {<br>        sharedPref.edit().putBoolean(key, value).apply()<br>    }</pre><pre>    fun getLong(key: String, defaultValue: Long = 0L): Long {<br>        return sharedPref.getLong(key, defaultValue)<br>    }</pre><pre>    fun putLong(key: String, value: Long) {<br>        sharedPref.edit().putLong(key, value).apply()<br>    }<br>}</pre><h3>Breaking Down the Implementation</h3><h3>The @Singleton Annotation</h3><pre>@Singleton<br>class DataStore @Inject constructor(@ApplicationContext val context: Context)</pre><p>The @Singleton annotation ensures that only one instance of DataStore exists throughout the app&#39;s lifecycle. This is crucial for consistency and performance.</p><h3>Constructor Injection</h3><p>The @Inject annotation tells Hilt to handle the instantiation of this class. The @ApplicationContext qualifier ensures we receive the application context, not an activity context, preventing memory leaks.</p><h3>Private SharedPreferences Instance</h3><pre>private val sharedPref: SharedPreferences = <br>    context.getSharedPreferences(&quot;AuthFile&quot;, Context.MODE_PRIVATE)</pre><p>We keep the SharedPreferences instance private to enforce encapsulation. All interactions must go through our DataStore methods.</p><h3>String Operations</h3><pre>fun getValue(key: String, defaultValue: String = &quot;&quot;): String {<br>    return sharedPref.getString(key, defaultValue) ?: defaultValue<br>}</pre><pre>fun putValue(key: String, value: String) {<br>    sharedPref.edit().putString(key, value).apply()<br>}</pre><p>Our string methods use Kotlin’s default parameters and the Elvis operator for clean, concise code.</p><h3>Utility Methods</h3><p>The contains(), remove(), and clear() methods provide essential functionality for managing stored data, especially useful during logout or data cleanup operations.</p><h3>Using the DataStore</h3><h3>Setting Up Hilt in Your Application</h3><p>First, annotate your Application class:</p><pre>@HiltAndroidApp<br>class MyApplication : Application()</pre><h3>Injecting DataStore into Your Classes</h3><p>In a ViewModel:</p><pre>@HiltViewModel<br>class AuthViewModel @Inject constructor(<br>    private val dataStore: DataStore<br>) : ViewModel() {<br>    <br>    fun saveAuthToken(token: String) {<br>        dataStore.putValue(&quot;auth_token&quot;, token)<br>    }<br>    <br>    fun getAuthToken(): String {<br>        return dataStore.getValue(&quot;auth_token&quot;)<br>    }<br>    <br>    fun logout() {<br>        dataStore.clear()<br>    }<br>}</pre><p>In a Repository:</p><pre>class AuthRepository @Inject constructor(<br>    private val dataStore: DataStore,<br>    private val apiService: ApiService<br>) {<br>    fun isUserLoggedIn(): Boolean {<br>        return dataStore.contains(&quot;auth_token&quot;)<br>    }<br>    <br>    suspend fun login(username: String, password: String) {<br>        val token = apiService.login(username, password)<br>        dataStore.putValue(&quot;auth_token&quot;, token)<br>    }<br>}</pre><h3>Best Practices</h3><h3>Use Constants for Keys</h3><p>Create a companion object or separate object class for keys:</p><pre>object PreferenceKeys {<br>    const val AUTH_TOKEN = &quot;auth_token&quot;<br>    const val USER_ID = &quot;user_id&quot;<br>    const val IS_FIRST_LAUNCH = &quot;is_first_launch&quot;<br>}</pre><h3>Consider Using commit() for Critical Data</h3><p>While apply() is asynchronous and generally preferred, use commit() for critical data that must be saved immediately:</p><pre>fun putValueSync(key: String, value: String): Boolean {<br>    return sharedPref.edit().putString(key, value).commit()<br>}</pre><h3>Add Logging for Debugging</h3><p>For development builds, consider adding logging:</p><pre>fun putValue(key: String, value: String) {<br>    if (BuildConfig.DEBUG) {<br>        Log.d(&quot;DataStore&quot;, &quot;Saving: $key = $value&quot;)<br>    }<br>    sharedPref.edit().putString(key, value).apply()<br>}</pre><h3>When to Use This Approach</h3><p>This DataStore wrapper is ideal for:</p><ul><li>Authentication tokens and user credentials</li><li>App settings and preferences</li><li>Feature flags</li><li>Small amounts of primitive data</li></ul><h3>When to Consider Alternatives</h3><p>Consider other solutions for:</p><ul><li><strong>Large datasets</strong>: Use Room Database</li><li><strong>Complex objects</strong>: Use Room with type converters or DataStore Preferences</li><li><strong>Structured data</strong>: Use Jetpack DataStore with Protocol Buffers</li><li><strong>Encrypted data</strong>: Use EncryptedSharedPreferences</li></ul><h3>Conclusion</h3><p>Creating a DataStore wrapper around SharedPreferences is a simple yet powerful pattern that promotes clean architecture in Android applications. By combining it with Hilt for dependency injection, we achieve a testable, maintainable, and scalable solution for managing app preferences.</p><p>This approach provides a solid foundation that can be extended with additional features like encryption, reactive flows with Kotlin Coroutines, or migration to Jetpack DataStore when needed.</p><p>The key takeaway is that even simple abstractions can significantly improve code quality and developer experience. Start with this basic implementation and evolve it as your application’s needs grow.</p><p><strong>Have you implemented a similar pattern in your Android apps? Share your experiences and improvements in the comments below!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bfd1a1ca222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronizing Threads in Java: Printing 1, 2, 3 in Sequence]]></title>
            <link>https://medium.com/@gauravbajaj/synchronizing-threads-in-java-printing-1-2-3-in-sequence-56ae6908900a?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ae6908900a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 02:12:29 GMT</pubDate>
            <atom:updated>2025-07-26T02:12:29.630Z</atom:updated>
            <content:encoded><![CDATA[<p>Multithreading is a powerful feature in Java that allows concurrent execution of multiple tasks. However, coordinating threads to achieve a specific order of execution can be challenging. In this blog post, we’ll explore how to create a Java program where three threads print the numbers 1, 2, and 3 in sequence repeatedly, ensuring perfect synchronization.</p><h3>The Problem</h3><p>We need three threads, each responsible for printing a specific number (1, 2, or 3). The output should follow a strict sequence: 1, 2, 3, 1, 2, 3, and so on. Without proper synchronization, threads might print their numbers in a random order due to the non-deterministic nature of thread scheduling.</p><h3>The Solution</h3><p>To achieve the desired sequence, we’ll use Java’s synchronization mechanisms, specifically the synchronized block, wait(), and notifyAll() methods. Here&#39;s the complete program:</p><pre>public class NumberPrinter {<br>    private static final Object lock = new Object();<br>    private static volatile int current = 1;<br><br>    public static void main(String[] args) {<br>        // Create three threads<br>        Thread thread1 = new Thread(new PrintTask(1));<br>        Thread thread2 = new Thread(new PrintTask(2));<br>        Thread thread3 = new Thread(new PrintTask(3));<br><br>        // Start the threads<br>        thread1.start();<br>        thread2.start();<br>        thread3.start();<br>    }<br><br>static class PrintTask implements Runnable {<br>        private final int number;<br><br>        public PrintTask(int number) {<br>            this.number = number;<br>        }<br>        @Override<br>        public void run() {<br>            while (true) {<br>                synchronized (lock) {<br>                    // Wait until it&#39;s this thread&#39;s turn<br>                    while (current != number) {<br>                        try {<br>                            lock.wait();<br>                        } catch (InterruptedException e) {<br>                            e.printStackTrace();<br>                        }<br>                    }<br>                    // Print the number<br>                    System.out.println(&quot;Thread &quot; + number + &quot; prints: &quot; + number);<br>                    // Update current number and notify others<br>                    current = (current % 3) + 1;<br>                    lock.notifyAll();<br>                    // Small delay to make output readable<br>                    try {<br>                        Thread.sleep(1000);<br>                    } catch (InterruptedException e) {<br>                        e.printStackTrace();<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>How It Works</h3><p>Let’s break down the key components of this program:</p><p><strong>Shared Lock Object</strong>:</p><ul><li>private static final Object lock = new Object(); creates a shared lock for synchronization.</li><li>All threads synchronize on this object to coordinate access.</li></ul><p><strong>Current Number Tracker</strong>:</p><ul><li>private static volatile int current = 1; tracks which number should be printed next.</li><li>The volatile keyword ensures visibility of changes across threads.</li></ul><p><strong>Thread Creation</strong>:</p><ul><li>Three threads are created, each with a PrintTask instance initialized with a number (1, 2, or 3).</li><li>Each thread runs the PrintTask&#39;s run() method.</li></ul><p><strong>Synchronization Logic</strong>:</p><ul><li>Inside the run() method, a synchronized block ensures only one thread can execute the critical section at a time.</li><li>The while (current != number) loop makes a thread wait if it&#39;s not its turn to print.</li><li>lock.wait() releases the lock and puts the thread in a waiting state.</li><li>After printing, the thread updates current to the next number (using modulo to cycle through 1, 2, 3).</li><li>lock.notifyAll() wakes up all waiting threads to check if it&#39;s their turn.</li></ul><ol><li><strong>Delay for Readability</strong>:</li></ol><ul><li>A Thread.sleep(1000) adds a 1-second delay between prints to make the output readable.</li></ul><h3>Output</h3><p>Running this program produces output like this:</p><pre>Thread 1 prints: 1<br>Thread 2 prints: 2<br>Thread 3 prints: 3<br>Thread 1 prints: 1<br>Thread 2 prints: 2<br>Thread 3 prints: 3<br>...</pre><p>The sequence is maintained indefinitely, with each thread printing its number in the correct order.</p><h3>Why Synchronization Matters</h3><p>Without synchronization, threads could print numbers in any order, leading to unpredictable output like “1, 3, 2” or “2, 1, 3”. The synchronized block, combined with wait() and notifyAll(), ensures that threads execute in the desired sequence, making the program deterministic.</p><h3>Key Takeaways</h3><ul><li>Use synchronized blocks to control access to shared resources.</li><li>Use wait() and notifyAll() for thread coordination.</li><li>The volatile keyword ensures variable visibility across threads.</li><li>Proper synchronization is crucial for predictable multithreaded behavior.</li></ul><p>This example demonstrates a practical application of thread synchronization in Java, a concept that’s essential for building robust concurrent applications. Try running the code and experimenting with different delays or additional threads to deepen your understanding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ae6908900a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Kotlin for LeetCode: Essential Constructs to Practice]]></title>
            <link>https://medium.com/@gauravbajaj/master-kotlin-for-leetcode-essential-constructs-to-practice-8aeb116d20a2?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aeb116d20a2</guid>
            <category><![CDATA[practice]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 19:10:33 GMT</pubDate>
            <atom:updated>2025-07-25T20:52:56.486Z</atom:updated>
            <content:encoded><![CDATA[<p>When diving into LeetCode problems with Kotlin, speed and fluency with core language constructs can make the difference between solving problems efficiently and getting stuck on syntax. This guide covers the essential Kotlin snippets and patterns you should master to become faster at competitive programming.</p><h3>🔄 Core Loops and Iteration</h3><p>Understanding Kotlin’s iteration patterns is crucial for traversing data structures efficiently.</p><h3>Basic For Loops</h3><pre>// Standard range (exclusive end)<br>for (i in 0 until n) { }<br><br>// Inclusive range<br>for (i in 0..n-1) { }<br><br>// Reverse iteration<br>for (i in n-1 downTo 0) { }<br><br>// Simple repetition<br>repeat(n) { <br>    // Execute n times<br>}<br><br>// Call a code block `n` times<br>repeat(n, {<br>    println(&quot;how are you?&quot;)<br>})</pre><h3>Collection Iteration</h3><pre>// Functional iteration<br>list.forEach { element -&gt; }<br>list.forEachIndexed { index, element -&gt; }<br><br>// Traditional loops still work<br>while (condition) { }<br><br>do { } while (condition)</pre><h3>📊 Array/List Operations</h3><p>Arrays and lists are the backbone of most LeetCode problems. Master these operations for quick data manipulation.</p><h3>Array Initialization</h3><pre>// Primitive arrays (more memory efficient)<br>val intArray = IntArray(n)                    // [0, 0, 0, ...]<br>val intArrayWithValue = IntArray(n) { 42 }    // [42, 42, 42, ...]<br>val doubleArray = DoubleArray(n)<br>val booleanArray = BooleanArray(n)<br><br>// Generic arrays (boxed types)<br>val objectArray = Array&lt;Int&gt;(n) { 0 }<br>val stringArray = Array&lt;String&gt;(n) { &quot;&quot; }<br>val customArray = Array(n) { index -&gt; index * 2 }<br><br>// Array literals<br>val literalArray = intArrayOf(1, 2, 3, 4, 5)<br>val stringLiterals = arrayOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</pre><h3><strong>List Allocation and Creation</strong></h3><pre>// Empty mutable lists<br>val mutableList = mutableListOf&lt;Int&gt;()<br>val arrayList = arrayListOf&lt;Int&gt;()<br>val linkedList = LinkedList&lt;Int&gt;()<br><br>// Pre-filled lists<br>val preFilledList = mutableListOf(1, 2, 3, 4, 5)<br>val repeatedList = MutableList(n) { 0 }           // [0, 0, 0, ...]<br>val indexedList = MutableList(n) { index -&gt; index }  // [0, 1, 2, ...]<br><br>// Immutable lists<br>val immutableList = listOf(1, 2, 3, 4, 5)<br>val emptyList = emptyList&lt;Int&gt;()<br>val singletonList = listOf(42)</pre><h3>Array ↔ List Conversions</h3><pre>// Array to List conversions<br>val intArray = intArrayOf(1, 2, 3, 4, 5)<br><br>// Primitive array to List&lt;Int&gt; (creates boxed objects)<br>val listFromIntArray = intArray.toList()<br>val mutableFromIntArray = intArray.toMutableList()<br><br>// Generic array conversions<br>val objectArray = arrayOf(1, 2, 3, 4, 5)<br>val listFromObjectArray = objectArray.toList()<br><br>// List to Array conversions<br>val list = listOf(1, 2, 3, 4, 5)<br><br>// List&lt;Int&gt; to IntArray (unboxes to primitives)<br>val intArrayFromList = list.toIntArray()<br>val intArrayFromCollection = list.toCollection(mutableListOf()).toIntArray()<br><br>// List to generic Array<br>val objectArrayFromList = list.toTypedArray()  // Array&lt;Int&gt;<br><br>// Specific type conversions<br>val doubleList = listOf(1.0, 2.0, 3.0)<br>val doubleArrayFromList = doubleList.toDoubleArray()<br><br>val stringList = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br>val stringArrayFromList = stringList.toTypedArray()  // Array&lt;String&gt;</pre><h3>Advanced Conversion Patterns</h3><pre>// Converting with transformation<br>val stringArray = arrayOf(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;)<br>val intListFromStrings = stringArray.map { it.toInt() }<br>val intArrayFromStrings = stringArray.map { it.toInt() }.toIntArray()<br><br>// Converting between different primitive types<br>val intArray = intArrayOf(1, 2, 3)<br>val longArray = intArray.map { it.toLong() }.toLongArray()<br>val doubleList = intArray.map { it.toDouble() }<br><br>// Converting nested collections<br>val listOfLists = listOf(listOf(1, 2), listOf(3, 4))<br>val arrayOfArrays = listOfLists.map { it.toIntArray() }.toTypedArray()<br><br>// From ranges to collections<br>val rangeToList = (1..10).toList()<br>val rangeToArray = (1..10).toList().toIntArray()</pre><h3>Memory Considerations</h3><pre>// Choose based on performance needs:<br><br>// Primitive arrays - most memory efficient, no boxing<br>val intArray = IntArray(1000)        // Uses actual int[] in JVM<br>val doubleArray = DoubleArray(1000)  // Uses actual double[] in JVM<br><br>// Generic arrays - boxed objects, more memory overhead<br>val objectArray = Array&lt;Int&gt;(1000) { 0 }  // Uses Integer[] in JVM<br><br>// Lists - most flexible but additional overhead<br>val list = MutableList(1000) { 0 }   // ArrayList&lt;Integer&gt; in JVM</pre><h3>Access and Modification</h3><pre>// Accessing elements<br>val element = arr[i]<br>val safeElement = list.getOrNull(i)  // Returns null if out of bounds<br><br>// Adding elements<br>list.add(element)<br>list += element<br>list.addAll(otherList)<br><br>// Size property<br>val size = arr.size<br>val listSize = list.size</pre><h3>📝 String Manipulation</h3><p>String problems are common in coding interviews. These operations will save you time.</p><h3>Common String Operations</h3><pre>// Conversion<br>val charArray = s.toCharArray()<br>val stringFromChars = charArray.joinToString(&quot;&quot;)<br><br>// Substring operations<br>val sub = s.substring(start, end)  // end is exclusive<br>val prefix = s.take(n)             // First n characters<br>val suffix = s.drop(n)             // Skip first n characters<br><br>// Transformations<br>val reversed = s.reversed()<br>val parts = s.split(&quot; &quot;)<br>val replaced = s.replace(&quot;old&quot;, &quot;new&quot;)</pre><h3>Character Utilities</h3><pre>// Character checks<br>c.isDigit()      // Is numeric digit<br>c.isLetter()     // Is alphabetic<br>c.isLowerCase()  // Is lowercase<br>c.isUpperCase()  // Is uppercase<br><br>// Conversions<br>c.digitToInt()   // &#39;5&#39; -&gt; 5<br>c.code           // Character to ASCII value<br>97.toChar()      // ASCII to character</pre><h3>🗂️ Collections and Data Structures</h3><p>Beyond basic arrays, these collections are essential for complex algorithms.</p><h3>HashMap/Map Initialization Techniques</h3><pre>// Empty maps<br>val mutableMap = mutableMapOf&lt;String, Int&gt;()<br>val hashMap = hashMapOf&lt;String, Int&gt;()<br>val linkedHashMap = linkedMapOf&lt;String, Int&gt;()  // Preserves insertion order<br><br>// Pre-filled maps with Pair syntax<br>val mapWithPairs = mutableMapOf(<br>    &quot;apple&quot; to 5,<br>    &quot;banana&quot; to 3,<br>    &quot;orange&quot; to 8<br>)<br><br>// Using hashMapOf for initial values<br>val hashMapWithValues = hashMapOf(<br>    1 to &quot;one&quot;,<br>    2 to &quot;two&quot;,<br>    3 to &quot;three&quot;<br>)<br><br>// Building maps with apply<br>val configuredMap = hashMapOf&lt;String, Int&gt;().apply {<br>    put(&quot;key1&quot;, 100)<br>    put(&quot;key2&quot;, 200)<br>    this[&quot;key3&quot;] = 300  // Alternative syntax<br>}<br><br>// From collections<br>val keys = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br>val values = listOf(1, 2, 3)<br>val mapFromLists = keys.zip(values).toMap()<br><br>// Associate functions - very useful for LeetCode!<br>val numbers = listOf(1, 2, 3, 4, 5)<br>val numberToSquare = numbers.associateWith { it * it }  // {1=1, 2=4, 3=9, ...}<br>val evenOddMap = numbers.associateBy { it % 2 }         // {1=1, 0=2} - last wins<br><br>// Frequency counting (common pattern)<br>val text = &quot;hello world&quot;<br>val charFrequency = text.groupingBy { it }.eachCount()  // {&#39;h&#39;=1, &#39;e&#39;=1, &#39;l&#39;=3, ...}<br><br>// Default value maps<br>val mapWithDefault = mutableMapOf&lt;String, Int&gt;().withDefault { 0 }<br>val count = mapWithDefault.getValue(&quot;missing&quot;)  // Returns 0 instead of throwing<br><br>// Concurrent maps (for multithreading)<br>val concurrentMap = java.util.concurrent.ConcurrentHashMap&lt;String, Int&gt;()</pre><h3>Advanced Map Operations</h3><pre>// Merging maps<br>val map1 = mapOf(&quot;a&quot; to 1, &quot;b&quot; to 2)<br>val map2 = mapOf(&quot;b&quot; to 3, &quot;c&quot; to 4)<br>val merged = map1 + map2  // {&quot;a&quot;=1, &quot;b&quot;=3, &quot;c&quot;=4} - map2 values win<br><br>// Computing values<br>val map = mutableMapOf&lt;String, Int&gt;()<br>map.compute(&quot;key&quot;) { key, value -&gt; (value ?: 0) + 1 }  // Increment or initialize<br>map.computeIfAbsent(&quot;key&quot;) { 0 }  // Set if absent<br>map.computeIfPresent(&quot;key&quot;) { key, value -&gt; value + 1 }  // Update if present<br><br>// Bulk operations<br>val filteredMap = map.filter { (key, value) -&gt; value &gt; 10 }<br>val transformedMap = map.mapValues { (key, value) -&gt; value * 2 }<br>val keyTransformed = map.mapKeys { (key, value) -&gt; key.uppercase() }</pre><h3>Sets and Other Collections</h3><pre>// Sets<br>val mutableSet = mutableSetOf&lt;Int&gt;()<br>val hashSet = hashSetOf&lt;Int&gt;()<br>val linkedHashSet = linkedSetOf&lt;Int&gt;()  // Preserves insertion order<br>val sortedSet = sortedSetOf&lt;Int&gt;()      // Maintains sorted order<br><br>// Pre-filled sets<br>val numbersSet = setOf(1, 2, 3, 4, 5)<br>val mutableNumbersSet = mutableSetOf(1, 2, 3, 4, 5)<br><br>// From collections<br>val listToSet = listOf(1, 1, 2, 2, 3).toSet()  // {1, 2, 3} - removes duplicates<br>val arrayToSet = intArrayOf(1, 2, 3).toSet()<br><br>// Usage<br>map[key] = value<br>val value = map[key]  // Returns nullable<br>val safeValue = map.getValue(key)  // Throws if key doesn&#39;t exist<br>val defaultValue = map.getOrDefault(key, 0)<br>val exists = key in set</pre><h3>Specialized Data Structures</h3><pre>// Stack (LIFO)<br>val stack = Stack&lt;Int&gt;()<br>stack.push(element)<br>val top = stack.pop()<br><br>// Queue/Deque (FIFO)<br>val deque = ArrayDeque&lt;Int&gt;()<br>deque.addLast(element)    // Enqueue<br>val first = deque.removeFirst()  // Dequeue<br><br>// Priority Queue (Heap)<br>val minHeap = PriorityQueue&lt;Int&gt;()<br>val maxHeap = PriorityQueue&lt;Int&gt;(compareByDescending { it })</pre><h3>🎯 Conditional and Comparison</h3><p>Kotlin’s expressive conditionals can make your code more concise and readable.</p><h3>Control Flow</h3><pre>// If as expression (returns value)<br>val result = if (condition) value1 else value2<br><br>// When expression (Kotlin&#39;s switch)<br>val result = when (value) {<br>    1 -&gt; &quot;one&quot;<br>    2, 3 -&gt; &quot;two or three&quot;<br>    in 4..10 -&gt; &quot;four to ten&quot;<br>    else -&gt; &quot;other&quot;<br>}</pre><h3>Utility Functions</h3><pre>// Min/Max operations<br>val maximum = maxOf(a, b, c)<br>val minimum = minOf(a, b, c)<br>val clamped = value.coerceIn(min, max<br><br>// Null safety<br>val safe = nullableValue?.property<br>val withDefault = nullableValue ?: defaultValue<br>val assertNotNull = nullableValue!!  // Use sparingly</pre><h3>⚡ Functional Programming Shortcuts</h3><p>These functional operations can replace complex loops with concise, readable code.</p><h3>Transformation Operations</h3><pre>// Transform elements<br>val doubled = list.map { it * 2 }<br>val filtered = list.filter { it &gt; 0 }<br>val sum = list.reduce { acc, element -&gt; acc + element }<br>val sumWithInitial = list.fold(0) { acc, element -&gt; acc + element }</pre><h3>Query Operations</h3><pre>// Boolean queries<br>val hasPositive = list.any { it &gt; 0 }<br>val allPositive = list.all { it &gt; 0 }<br>val noneNegative = list.none { it &lt; 0 }<br>val count = list.count { it &gt; 10 }<br><br>// Grouping and partitioning<br>val grouped = list.groupBy { it % 2 }  // Group by even/odd<br>val (evens, odds) = list.partition { it % 2 == 0 }</pre><h3>Advanced Operations</h3><pre>// Sorting<br>val sorted = list.sortedBy { it.property }<br>val sortedDescending = list.sortedByDescending { it }<br><br>// Combining<br>val zipped = list1.zip(list2) { a, b -&gt; a + b }<br>val pairs = list.zipWithNext { a, b -&gt; Pair(a, b) }</pre><h3>📏 Range and Progression</h3><p>Ranges are powerful for iteration and contains checks.</p><h3>Range Types</h3><pre>// Inclusive range<br>for (i in 1..10) { }        // 1, 2, ..., 10<br><br>// Exclusive range<br>for (i in 1 until 10) { }   // 1, 2, ..., 9<br><br>// Reverse range<br>for (i in 10 downTo 1) { }  // 10, 9, ..., 1<br><br>// Step progression<br>for (i in (1..10).step(2)) { }  // 1, 3, 5, 7, 9</pre><h3>Useful Range Operations</h3><pre>// Collection indices<br>for (i in list.indices) { }  // 0 until list.size<br><br>// Contains check<br>val inRange = value in 1..100</pre><h3>🛠️ Quick Utility Functions</h3><p>These Kotlin-specific features can make your code more elegant and efficient.</p><h3>Scope Functions</h3><pre>// also - perform action and return original object<br>val result = list.also { it.sort() }<br><br>// let - transform object<br>val length = nullableString?.let { it.length }<br><br>// apply - configure object<br>val list = mutableListOf&lt;Int&gt;().apply {<br>    add(1)<br>    add(2)<br>}<br><br>// run - execute block and return result<br>val result = run {<br>    val a = computeA()<br>    val b = computeB()<br>    a + b<br>}</pre><h3>Conditional Operations</h3><pre>// Execute only if condition is met<br>val result = value.takeIf { it &gt; 0 }        // Returns value or null<br>val result = value.takeUnless { it &lt; 0 }    // Returns value or null</pre><h3>🔄 Type Conversions</h3><p>Quick conversions between common types used in algorithms.</p><h3>Numeric Conversions</h3><pre>// String to numbers<br>val int = &quot;123&quot;.toInt()<br>val long = &quot;123&quot;.toLong()<br>val double = &quot;123.45&quot;.toDouble()<br><br>// Numbers to string<br>val str = 123.toString()<br><br>// Character conversions<br>val digit = &#39;5&#39;.digitToInt()  // Returns 5<br>val ascii = &#39;A&#39;.code          // Returns 65<br>val char = 65.toChar()        // Returns &#39;A&#39;</pre><h3>Safe Conversions</h3><pre>// Safe conversions (return null on failure)<br>val int = &quot;123abc&quot;.toIntOrNull()  // Returns null<br>val number = string.toIntOrNull() ?: 0  // Default value</pre><h3>🎯 Practice Strategy</h3><p>To build muscle memory with these constructs:</p><ol><li><strong>Start Small</strong>: Practice each construct in isolation before combining them</li><li><strong>Focus on Speed</strong>: Time yourself writing common patterns</li><li><strong>Build Progressively</strong>: Combine constructs to solve increasingly complex problems</li><li><strong>Use Templates</strong>: Create reusable code snippets for common patterns</li><li><strong>Practice Daily</strong>: Consistent practice builds the fluency you need for interviews</li></ol><p>Remember, the goal isn’t to memorize every function, but to develop intuition for which tools to reach for when solving different types of problems. With practice, these patterns will become second nature, allowing you to focus on the algorithmic challenges rather than fighting with syntax.</p><p><em>Happy coding! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aeb116d20a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Interview Prep: Read Local JSON with MVVM + Compose]]></title>
            <link>https://medium.com/@gauravbajaj/android-interview-prep-read-local-json-with-mvvm-compose-fffd482b2141?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffd482b2141</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[andoid]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 18:23:45 GMT</pubDate>
            <atom:updated>2025-07-25T17:29:34.446Z</atom:updated>
            <content:encoded><![CDATA[<p>Reading local JSON files is a common Android interview question — simple on the surface, but it reveals a lot about how well you understand app architecture and modern development practices.</p><p>To prepare, I built a small app that reads user data from a JSON file in the assets folder and displays it using:</p><ul><li>🧩 <strong>MVVM architecture</strong></li><li>📦 <strong>ViewModel + Kotlin Flow</strong> for state management</li><li>📄 <strong>Moshi</strong> for JSON parsing</li><li>🖼️ <strong>Jetpack Compose</strong> for the UI</li></ul><p>The goal was to show how you can load structured data locally and render it in a reactive UI — all using clean, testable layers. It’s a great interview-friendly app that covers architecture, data handling, and Compose basics without involving a remote backend.</p><p>Here is the <strong>step-by-step guide</strong> to build an Android app <strong>from an empty project</strong> using the following technologies:</p><ul><li>✅ Kotlin</li><li>✅ Jetpack Compose</li><li>✅ MVVM architecture</li><li>✅ ViewModel</li><li>✅ Kotlin Flow</li><li>✅ Moshi for JSON serialization</li></ul><h3>✅ Step 0: Create an Empty Compose Project</h3><ol><li><strong>Open Android Studio</strong> → New Project → Choose Empty Compose Activity</li><li><strong>Project Name</strong>: e.g., MoshiFlowApp</li><li><strong>Language</strong>: Kotlin</li><li><strong>Minimum SDK</strong>: API 24+</li></ol><h3><strong>✅ Step 1: Setup Dependencies</strong></h3><p>Open build.gradle (app) and add the following:</p><pre>plugins {<br>    id &#39;com.android.application&#39;<br>    id &#39;org.jetbrains.kotlin.android&#39;<br>    kotlin(&quot;kapt&quot;) // for Moshi codegen<br>}<br><br>android {<br>    compileSdk = 34<br><br>    defaultConfig {<br>        applicationId = &quot;com.example.moshiflowapp&quot;<br>        minSdk = 24<br>        targetSdk = 34<br>        versionCode = 1<br>        versionName = &quot;1.0&quot;<br>    }<br><br>    buildFeatures {<br>        compose true<br>    }<br><br>    composeOptions {<br>        kotlinCompilerExtensionVersion = &quot;1.5.0&quot;<br>    }<br><br>    kotlinOptions {<br>        jvmTarget = &quot;1.8&quot;<br>    }<br>}<br><br>dependencies {<br>    // Jetpack Compose<br>    implementation(&quot;androidx.activity:activity-compose:1.8.0&quot;)<br>    implementation(&quot;androidx.compose.ui:ui:1.5.0&quot;)<br>    implementation(&quot;androidx.compose.material3:material3:1.1.2&quot;)<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1&quot;)<br><br>    // ViewModel and LiveData<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1&quot;)<br><br>    // Kotlin Coroutines + Flow<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3&quot;)<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3&quot;)<br><br>    // Moshi for JSON parsing<br>    implementation(&quot;com.squareup.moshi:moshi:1.15.0&quot;)<br>    implementation(&quot;com.squareup.moshi:moshi-kotlin:1.15.0&quot;)<br>    kapt(&quot;com.squareup.moshi:moshi-kotlin-codegen:1.15.0&quot;)<br><br>    // Optional - Retrofit if you want to fetch from API<br>    implementation(&quot;com.squareup.retrofit2:retrofit:2.9.0&quot;)<br>    implementation(&quot;com.squareup.retrofit2:converter-moshi:2.9.0&quot;)<br>}</pre><p>Place a file like users.json in src/main/assets:</p><pre>[<br>  { &quot;id&quot;: 1, &quot;name&quot;: &quot;Alice&quot;, &quot;email&quot;: &quot;alice@example.com&quot; },<br>  { &quot;id&quot;: 2, &quot;name&quot;: &quot;Bob&quot;, &quot;email&quot;: &quot;bob@example.com&quot; }<br>]</pre><p>Sync the project.</p><h3><strong>✅ Step 2: Create Data Model (Moshi + Kotlin)</strong></h3><p>Create a model package and define a JSON model:</p><pre>// model/User.kt<br>package com.example.moshiflowapp.model<br><br>import com.squareup.moshi.JsonClass<br><br>@JsonClass(generateAdapter = true)<br>data class User(<br>    val id: Int,<br>    val name: String,<br>    val email: String<br>)</pre><h3><strong>✅ Step 3: Create Repository with Kotlin Flow</strong></h3><p>Create a repository package:</p><pre>// repository/UserRepository.kt<br>package com.example.moshiflowapp.repository<br><br>import android.content.Context<br>import com.example.localjsonapp.model.User<br>import com.squareup.moshi.Moshi<br>import com.squareup.moshi.Types<br>import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory<br>import kotlinx.coroutines.delay<br>import kotlinx.coroutines.flow.Flow<br>import kotlinx.coroutines.flow.flow<br><br>class UserRepository(private val context: Context) {<br>    fun getUsers(): Flow&lt;List&lt;User&gt;&gt; = flow {<br>        delay(1000) // simulate network delay<br>        /**<br>         * 1. Read the json file<br>         * 2. Convert the json file to the list<br>         *    a. Create moshi<br>         *    b. Create moshi adapter<br>         *    c. Convert<br>         * 3. Emit the list<br>         */<br>        val jsonString = context.assets.open(&quot;users.json&quot;).bufferedReader().use { it.readText() }<br>        val moshi = Moshi.Builder()<br>            .add(KotlinJsonAdapterFactory())<br>            .build()<br>        val users = moshi<br>            .adapter&lt;List&lt;User&gt;&gt;(Types.newParameterizedType(List::class.java, User::class.java))<br>            .fromJson(jsonString) ?: emptyList()<br>        emit(users)<br>    }<br>}</pre><h3><strong>✅ Step 4: Create ViewModel</strong></h3><p>Create a viewmodel package:</p><pre>// viewmodel/UserViewModel.kt<br>package com.example.moshiflowapp.viewmodel<br><br>import android.app.Application<br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.viewModelScope<br>import com.example.moshiflowapp.model.User<br>import com.example.moshiflowapp.repository.UserRepository<br>import kotlinx.coroutines.flow.MutableStateFlow<br>import kotlinx.coroutines.flow.StateFlow<br>import kotlinx.coroutines.launch<br><br>class UserViewModel(val context: Application) : ViewModel() {<br>    private val repository = UserRepository(context.applicationContext)<br><br>    private val _users = MutableStateFlow&lt;List&lt;User&gt;&gt;(emptyList())<br>    val users: StateFlow&lt;List&lt;User&gt;&gt; = _users<br><br>    init {<br>        loadUsers()<br>    }<br><br>    private fun loadUsers() {<br>        viewModelScope.launch {<br>            repository.getUsers().collect {<br>                _users.value = it<br>            }<br>        }<br>    }<br>}</pre><h3><strong>✅ Step 5: Create UI with Compose</strong></h3><p>Update your MainActivity.kt:</p><pre>// MainActivity.kt<br>package com.example.moshiflowapp<br><br>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import androidx.lifecycle.viewmodel.compose.viewModel<br>import com.example.moshiflowapp.ui.UserScreen<br>import com.example.moshiflowapp.viewmodel.UserViewModel<br><br>class MainActivity : ComponentActivity() {<br>    val userViewModel = UserViewModel(this.application)<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            val users = userViewModel.users.collectAsStateWithLifecycle()<br>            LaunchedEffect(Unit) {<br>                userViewModel.loadUsers()<br>            }<br>            UserScreen(userViewModel)<br>        }<br>    }<br>}</pre><p>Then in ui/UserScreen.kt:</p><pre>// ui/UserScreen.kt<br>package com.example.moshiflowapp.ui<br><br>import androidx.compose.foundation.layout.*<br>import androidx.compose.material3.*<br>import androidx.compose.runtime.*<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.unit.dp<br>import com.example.moshiflowapp.viewmodel.UserViewModel<br>import androidx.lifecycle.compose.collectAsStateWithLifecycle<br><br>@Composable<br>fun UserScreen(users: List&lt;User&gt;) {<br>    val users by viewModel.users.collectAsStateWithLifecycle()<br><br>    Scaffold(<br>        topBar = {<br>            TopAppBar(title = { Text(&quot;User List&quot;) })<br>        }<br>    ) { padding -&gt;<br>        Column(modifier = Modifier<br>            .padding(padding)<br>            .padding(16.dp)) {<br>            users.forEach { user -&gt;<br>                Text(text = &quot;${user.name} - ${user.email}&quot;)<br>                Spacer(modifier = Modifier.height(8.dp))<br>            }<br><br>            if (users.isEmpty()) {<br>                CircularProgressIndicator()<br>            }<br>        }<br>    }<br>}</pre><h3><strong>✅ Step 6: Run and Test</strong></h3><ul><li>Run the app on an emulator or device.</li><li>You should see a loading spinner and then a list of users.</li></ul><h3>✅ Summary</h3><p>You now have:</p><ul><li>✅ MVVM architecture with UserRepository, UserViewModel, and UserScreen</li><li>✅ Jetpack Compose UI</li><li>✅ Kotlin Flow for reactive state</li><li>✅ Moshi for JSON modeling</li></ul><p>Disclaimer: Chat GPT was used to refine the steps to write this blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffd482b2141" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Sense of Mixed-Up JSON with Moshi]]></title>
            <link>https://medium.com/@gauravbajaj/making-sense-of-mixed-up-json-with-moshi-df75bf7bcdec?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/df75bf7bcdec</guid>
            <category><![CDATA[moshi]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 17:01:37 GMT</pubDate>
            <atom:updated>2025-07-16T17:01:37.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GyWrdfwBsP3FlHIi7LbPQ.png" /><figcaption>Polymorphic Json Blob</figcaption></figure><h3>TL;DR</h3><ul><li>PolymorphicJsonAdapterFactory helps parse polymorphic JSON using a discriminator field like &quot;type&quot;.</li><li>Register subtypes with .withSubtype()</li><li>Use .withDefaultValue() for resilience against unknown types.</li><li>It’s perfect for sealed class hierarchies or abstract types in Kotlin.</li></ul><h3>The Main Story</h3><p>Ever find yourself with a list of things that are <em>sort of</em> the same, but also different? Imagine you’re building a drawing app. You have circles, rectangles, and triangles. In your code, they might all be a type of Shape.</p><pre>sealed class Shape<br>data class Circle(val radius: Double) : Shape()<br>data class Rectangle(val width: Double, val height: Double) : Shape()</pre><p>Easy enough. Now, you want to save your drawing. JSON is the obvious choice. You might structure it like this, adding a little “type” field to know which is which:</p><pre>[<br>  { &quot;type&quot;: &quot;circle&quot;, &quot;radius&quot;: 2.5 },<br>  { &quot;type&quot;: &quot;rectangle&quot;, &quot;width&quot;: 4.0, &quot;height&quot;: 3.0 }<br>]</pre><p>Looks perfect. But when you ask Moshi to turn this back into a List&lt;Shape&gt;, it gets confused and throws an error.</p><p>Why? Moshi sees Shape, but Shape is just an idea, not a concrete thing. It doesn&#39;t know whether to build a Circle or a Rectangle. It needs a clue.</p><p>This is where you hit a wall and might think, “Damn, do I have to write a custom parser for this?”</p><p>Nope! Moshi has a wonderful little tool for exactly this situation: <strong>PolymorphicJsonAdapterFactory</strong>.</p><p>It sounds complicated, but it’s not. Think of it as a smart mail sorter for your JSON. You just have to give it a few simple instructions:</p><ul><li><strong>What you’re sorting:</strong> Shape objects.</li><li><strong>The label to look for:</strong> The field named &quot;type&quot;.</li><li><strong>Where each label goes:</strong> If the label says &quot;circle&quot;, put it in the Circle bin. If it says &quot;rectangle&quot;, put it in the Rectangle bin.</li></ul><p>Here’s what those instructions look like in code:</p><pre>val moshi = Moshi.Builder()<br>  .add(<br>    PolymorphicJsonAdapterFactory.of(Shape::class.java, &quot;type&quot;)<br>      .withSubtype(Circle::class.java, &quot;circle&quot;)<br>      .withSubtype(Rectangle::class.java, &quot;rectangle&quot;)<br>  )<br>  .build()</pre><p>And that’s it. That’s the entire setup.</p><p>Suddenly, Moshi understands. It peeks at the &quot;type&quot; field for each object and instantly knows which data class to use. Your JSON turns into a perfect list of Kotlin objects.</p><p><strong>But what if you get a weird shape you don’t recognize?</strong></p><p>You don’t want your app to crash. The adapter has you covered. You can tell it to use a “catch-all” or default option for anything it doesn’t recognize.</p><pre>.withDefaultValue(UnknownShape()) // A fallback so the app doesn&#39;t break</pre><p>So, the next time your API gives you a list of items with a &quot;kind&quot; or &quot;objectType&quot; field, don&#39;t sweat it. Just reach for PolymorphicJsonAdapterFactory. It&#39;s Moshi&#39;s super-friendly way of handling data that comes in different shapes and sizes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df75bf7bcdec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Strategic Guide to Building Your Professional Developer Profile ]]></title>
            <link>https://medium.com/@gauravbajaj/a-strategic-guide-to-building-your-professional-developer-profile-924da39bfbe1?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/924da39bfbe1</guid>
            <category><![CDATA[branding]]></category>
            <category><![CDATA[branding-strategy]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 17:02:58 GMT</pubDate>
            <atom:updated>2025-07-07T17:02:58.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYdG7RNsdlT9GDx8sMVqMw.png" /><figcaption>Tech Career Strategies</figcaption></figure><p>Building a strong professional developer profile is a critical investment in your long-term career success and “findability” in the tech industry. Committing to a focused, one-year effort can yield rewards that last a lifetime. This guide outlines a comprehensive strategy to help you create a robust and discoverable professional presence.</p><h3>I. Overall Strategy &amp; Mindset</h3><p>A successful profile is built on a solid strategy and the right mindset. Prioritize making yourself <strong>findable</strong> by consistently creating and sharing high-quality work. Embrace a philosophy of <strong>continuous improvement</strong> in everything you produce.</p><p>Before publishing anything, ask yourself the crucial question: <strong>“So what?”</strong> This ensures your content provides genuine value to your audience. Remember that the results of your efforts will compound over time, so maintain your momentum and believe in your ability to create content that is better than what’s already out there.</p><h3>II. GitHub: The Foundation of Your Profile</h3><p>Your projects are the cornerstone of your entire professional profile. Every blog post, social media update, and technical discussion should be driven by the work you showcase on GitHub.</p><ul><li><strong>Build Meaningful Projects:</strong> Focus on projects that demonstrate technical difficulty. Contributing to or creating <strong>open-source libraries</strong> offers immense learning opportunities and long-term benefits.</li><li><strong>Start Small, Grow Big:</strong> Begin with smaller projects to build confidence and gain a sense of accomplishment before tackling more complex challenges.</li><li><strong>Stay Current:</strong> Keep your projects updated with the latest technologies. This not only showcases a commitment to continuous learning but also keeps you interview-ready.</li><li><strong>Strategic Naming:</strong> Name your repositories with relevant keywords (e.g., “Golang-Backend-Clean-Architecture”) to improve their visibility on search engines.</li><li><strong>Pin Your Best Work:</strong> Pin your most important projects and significant contributions to the top of your GitHub profile to ensure visitors see your best work first.</li></ul><h3>Crafting the Perfect README</h3><p>Your README is the front door to your project. Make it count.</p><ul><li><strong>Include Visuals:</strong> Use small, compressed images (10–20 KB) to showcase your work without slowing down page load times. Tools like <strong>TinyPNG</strong> are great for this.</li><li><strong>Provide Clear Instructions:</strong> Offer clear, step-by-step instructions on how to build and run the project.</li><li><strong>Show the Structure:</strong> Include the project’s file structure (using a tool like tree) to give others a quick overview.</li><li><strong>Add Context:</strong> Write a concise project description and link to any relevant blog posts you’ve written about it.</li><li><strong>Use Relevant Tags:</strong> Add appropriate tags (e.g., “Android,” “MVVM-architecture,” “Kotlin-Coroutine”) but avoid over-tagging. Remember that search engine algorithms prioritize text, so focus on descriptive content.</li></ul><h3>III. Blogging: Showcase Your Expertise</h3><p>Your projects provide a rich source of content for technical blog posts. Write about the challenges you faced, the solutions you discovered, and the concepts you researched while building.</p><ul><li><strong>Write for Your Audience:</strong> Choose strategic blog titles based on what people are actively searching for. Use Google Incognito mode to research popular queries.</li><li><strong>Create Comprehensive Content:</strong> Google rewards depth. Aim for long-form content (ideally <strong>1,800–3,000 words</strong>) that thoroughly covers a topic. Before writing, read everything you can on the subject to ensure your post is the most exhaustive and valuable resource available.</li><li><strong>Link Strategically:</strong> Smartly link back to your GitHub projects within your blog posts to demonstrate the practical application of your knowledge.</li><li><strong>Publish Consistently:</strong> Set a consistent publishing schedule, such as one post every two weeks, to build an audience and momentum over time.</li></ul><h3>Your Publishing Platform Strategy</h3><ul><li><strong>Own Your Domain:</strong> Purchase your own domain (e.g., .com, .dev, .tech) to create a central hub for your professional brand. This is your digital real estate.</li><li><strong>Host Smart:</strong> Use a free, fast, and reliable service like <strong>GitHub Pages</strong> for your blog. It offers superior performance and SEO benefits compared to older platforms.</li><li><strong>Publish First, Syndicate Later:</strong> Always publish new articles on <strong>your own domain first</strong>. Afterward, republish on platforms like Medium, Dev.to, and Hashnode, making sure to set the <strong>canonical URL</strong> back to your original post. This prevents SEO penalties and leverages the audiences of these larger platforms.</li></ul><h3>IV. Social Media: Amplify Your Reach</h3><p>Break down your projects and long-form blog posts into digestible, short-form content for social media platforms like LinkedIn and Twitter.</p><ul><li><strong>Use Visuals:</strong> On platforms like LinkedIn, use relevant and eye-catching images (created with tools like <strong>Canva</strong>) to make your posts stand out in the feed.</li><li><strong>Master the Algorithm:</strong> On LinkedIn, write 3–4 lines of text to make the post collapse. This encourages users to click “<strong>…more</strong>,” which signals valuable content to the algorithm and boosts your post’s reach. When sharing a link, post an image with text first and add the link in a comment to avoid having your reach penalized.</li><li><strong>Engage with Communities:</strong> Share your work and insights on relevant subreddits (e.g., r/androiddev, r/golang) to spark discussion and gain visibility within niche communities.</li></ul><h3>V. Stack Overflow: Give and Take</h3><p>Actively participating on Stack Overflow is a powerful way to build your reputation and drive traffic to your work.</p><ul><li><strong>Answer Questions:</strong> Focus on answering recent and difficult questions in your areas of expertise.</li><li><strong>Link with Purpose:</strong> When appropriate, strategically link to your relevant blog posts within your answers. A single, well-placed backlink from Stack Overflow can provide immense SEO value.</li><li><strong>Find Project Ideas:</strong> Pay attention to the latest unanswered questions. If you see recurring problems or a need for a library that doesn’t exist yet, you’ve just found your next project idea.</li></ul><h3>VI. Utilizing AI Tools</h3><p>AI tools like ChatGPT can be powerful assistants, but they should not be the author.</p><ul><li><strong>Brainstorm and Refine:</strong> Use AI to brainstorm project or blog ideas, check your grammar, and optimize the clarity and flow of your content.</li><li><strong>Write It Yourself:</strong> The core content must be genuinely written by you. Search engines can penalize AI-generated content, and more importantly, your unique story and expertise are what make your profile valuable. AI can’t replicate that.</li></ul><h3>VII. General Profile Presentation</h3><p>Finally, ensure your entire online presence is cohesive and professional. Fill out all sections of your <strong>GitHub and LinkedIn profiles</strong>, and make sure all of your platforms are linked to one another to create a seamless experience for anyone looking to learn more about you and your work.</p><p>Credites:</p><p><em>This guide was created based on notes and highlights gathered from a sessions conducted by </em><a href="https://medium.com/u/521fcfd1d272"><em>Amit Shekhar</em></a><em>. Amit is a renounced name in Android community as Tech Education content creator. He is a passionate person who has helped thousands of Android developers across the globe through his Outcome School. Please follow him for knowledgable Tech content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=924da39bfbe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debounce: An Overload Shopping Cart Scenario]]></title>
            <link>https://medium.com/@gauravbajaj/debounce-an-overload-shopping-car-scenario-15ec466ecf2d?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/15ec466ecf2d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 21:51:47 GMT</pubDate>
            <atom:updated>2025-07-04T06:45:35.556Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TLDR:</strong> debounce ignores a rapid series of events and only acts on the very last one after a specified pause. It&#39;s like telling an app, &quot;Don&#39;t do anything until I&#39;ve stopped clicking/typing for a moment.&quot;</p><p>This is useful for things like search bars or quantity buttons to prevent the app from doing heavy work on every single input, saving resources and preventing lag.</p><p>Here is the diagram that shows it in action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VckNgu6LCTj0lNEtPpLMvQ.png" /></figure><p>input events, only the last event in a cluster (after a 300ms pause) is actually processed.</p><h3>The Problem: A “Smart” Shopping Cart Overload</h3><p>Imagine you are developing an e-commerce application. One of its core features is a “smart” shopping cart. For each item in the cart, the user can adjust the quantity using “+” and “-” buttons.</p><p>Every time the quantity changes, the application must perform a series of important, resource-intensive actions:</p><ol><li><strong>Validate Inventory:</strong> Check if the requested quantity is available in stock. This requires a network call to your backend server.</li><li><strong>Recalculate Totals:</strong> Update the item’s subtotal and the cart’s overall total price.</li><li><strong>Check Promotions:</strong> See if the new quantity qualifies for any special discounts (e.g., “buy 2, get 1 free”). This might also involve a separate network call.</li></ol><p>The issue arises when users click the “+” or “-” buttons very rapidly. For instance, a user might click the “+” button five times in less than a second to increase an item’s quantity from 1 to 6.</p><p>Without a proper control mechanism, the application will fire off five separate sets of network calls and recalculations in that short span. This leads to:</p><ul><li><strong>Server Overload:</strong> The backend is bombarded with unnecessary API requests.</li><li><strong>UI Lag:</strong> The UI might flicker or feel sluggish as it tries to update with the results of each intermediate state (quantity 2, 3, 4, 5), only for it to be immediately replaced by the next update.</li><li><strong>Race Conditions:</strong> Network call responses might arrive out of order, leading to an inconsistent and incorrect final cart state.</li></ul><p>Your task is to refactor the shopping cart logic to ensure that the validation and recalculation processes only happen <em>after</em> the user has finished adjusting the quantity and has paused for a reasonable moment.</p><p>Here is a complete, runnable Kotlin solution that simulates this scenario and solves it elegantly using the debounce operator from Kotlin Flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/062e1c91d6784813a8ca7ab08f9ede22/href">https://medium.com/media/062e1c91d6784813a8ca7ab08f9ede22/href</a></iframe><p>This solution effectively solves our problem. As you can see from the output of the main function, even though the quantity is updated five times in rapid succession, the expensive updateCart function is only called once, 300ms after the final quantity was set. This prevents the server overload, UI lag, and potential race conditions of the original problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15ec466ecf2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Curious Case of the  Chatty Android App]]></title>
            <link>https://medium.com/@gauravbajaj/the-curious-case-of-the-chatty-app-80ea0f654e9d?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ea0f654e9d</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[behavior-question]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 21:14:09 GMT</pubDate>
            <atom:updated>2025-07-15T17:24:01.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Curious Case of the Chatty Android App</h3><p><strong>A Production Bug That Changed How We Released Features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8GFIEbazWhOujQdlLoYdQ.png" /><figcaption>A real case of works my machine</figcaption></figure><h3>The Bright Idea and Smooth Launch</h3><p>As part of a broader initiative to improve perceived performance, I led the design and implementation of a feature that preloaded user data at app launch. The idea was to make the first screen instantly responsive. I worked across product, backend, and QA teams to align expectations and verify backend readiness for the added load. We ran regression tests, battery usage scenarios, and device matrix testing. The rollout was smooth, and we considered it a success.</p><h3>The Mysterious Traffic Surge</h3><p>Three days after deployment, our monitoring dashboards reported a 5x spike in traffic to one of our core APIs. Backend autoscaling kicked in, and latency warnings triggered. We hadn’t launched any campaigns, and user traffic remained normal.</p><p>I took the ownership of the incident response, assembled a cross-functional team (mobile, backend, QA, SRE), and initiated a deep-dive investigation.</p><h3>Unmasking the Culprit</h3><p>We discovered that on specific Android devices — especially older models or those with aggressive memory and battery management — the OS was terminating our app shortly after launch. Since our preloading logic was tied to onCreate() of the Application creation path, each restart re-triggered the fetch.</p><p>This resulted in a loop: app starts → fetch fires → app gets killed → app restarts → fetch fires again. Our QA hadn’t accounted for this specific lifecycle behavior.</p><h3>Crisis Mode and Fast Fix</h3><p>I led the immediate mitigation by remotely disabling the feature using our internal feature flag system. QA verified the behavior on affected devices, and SRE confirmed backend load began to normalize within hours.</p><h3>Lessons Learned and Long-Term Changes</h3><p>Recognizing this as a <strong>systemic blind spot</strong>, I led a technical postmortem and drove the following org-wide changes:</p><ul><li><strong>Implemented dynamic feature flags</strong> on all user-facing features, with rollback capability.</li><li>Introduced <strong>staged rollout processes</strong> at the infrastructure level — starting with 1% of the user base, monitored by custom metrics and alerts.</li><li>Worked with DevOps to define <strong>release gates and canary monitors</strong> in our CI/CD pipelines.</li><li>Expanded our <strong>device testing matrix</strong> to include low-memory and battery-constrained devices, and added <strong>lifecycle simulation tools</strong> in our test harness.</li><li>Documented Android-specific lifecycle edge cases for engineering onboarding and design reviews.</li></ul><h3>Final Reflection</h3><p>While it was stressful in the moment, this bug led to meaningful process changes that significantly reduced our production risk going forward. It made our team more resilient and helped us mature our release strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ea0f654e9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dash Dilemma: When a Small Design Request Has Big Consequences]]></title>
            <link>https://medium.com/@gauravbajaj/the-dash-dilemma-when-a-small-design-request-has-big-consequences-5be67f56e6a3?source=rss-e08f1b8fda3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be67f56e6a3</guid>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[conflict-resolution]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gaurav Bajaj]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 21:33:15 GMT</pubDate>
            <atom:updated>2025-06-25T00:02:12.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6ZzmlmmrLPlAKUVbDyKRQ.jpeg" /><figcaption>Team work</figcaption></figure><p>As developers, we often face seemingly minor design requests that hide significant technical complexities. One recent project highlighted this perfectly, teaching me a valuable lesson in collaborating with design teams.</p><h3>The Request: A Tiny Dash, A Big Problem</h3><p>We were building a new UI for a global product. The UI/UX designer wanted a specific date format: 3:30PM - 6:30PM (with spaces around the dash).</p><p>Our standard library, however, produced 3:30PM-6:30PM (no spaces).</p><p><strong>Designer’s Proposed:</strong> 3:30PM - 6:30PM</p><p><strong>Standard Library:</strong> 3:30PM-6:30PM</p><p>The difference was subtle, but the impact was not. Implementing that custom dash meant:</p><ul><li><strong>Extra Dev Work:</strong> About <strong>3–4 hours</strong> of custom coding.</li><li><strong>Maintenance Nightmare:</strong> Our product supports multiple languages and countries. This custom format would demand an additional <strong>2–3 days of multi-locale testing</strong> for <em>every</em> update to ensure it didn’t break translations or display incorrectly worldwide. This was a huge, hidden cost for a tiny aesthetic choice.</li></ul><h3>My Approach: Data, Visuals, and Collaboration</h3><p>Instead of just saying “no,” I prepared a clear case:</p><ol><li><strong>Quantified the Impact:</strong> I explained the 3-4 hours of initial work and the 2-3 days of recurring multi-locale testing.</li><li><strong>Proposed an Alternative:</strong> I advocated for our standard, maintenance-free format.</li><li><strong>Showed, Don’t Just Tell:</strong> Crucially, I shared <strong>screenshots</strong> of the standard format in action. Seeing it visually helped the designer understand that the minor difference was barely noticeable to users.</li><li><strong>Empathized &amp; Explained:</strong> I initiated a chat, acknowledging their vision first, then calmly laying out the technical and long-term costs. I emphasized my openness to their decision but highlighted the technical debt.</li></ol><h3>The Resolution: Win-Win for Product &amp; Team</h3><p>The designer appreciated the transparency and the visual evidence. They quickly agreed that the standard format was more than sufficient and that avoiding the significant development and testing overhead was the smarter move for our global product.</p><p>We implemented the standard format, saving valuable time and preventing future internationalization headaches.</p><h3>The Takeaway</h3><p>This experience reinforced that effective collaboration with design isn’t about rejecting ideas. It’s about <strong>transparently communicating the “why”</strong> behind technical decisions, backing it with data, and offering practical, sustainable alternatives. When engineers and designers unite with a common understanding, everyone wins, and the product thrives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be67f56e6a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>