Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Detekt : static code analysis tool for Kotlin

Detekt is a static code analysis tool for Kotlin that inspects your Android/Kotlin codebase for:

  •  Code smells
  •  Performance issues
  •  Potential memory/context leaks
  •  Style violations
  • Complexity, nesting, duplication, and more

Think of it as Kotlin’s equivalent of Lint or SonarQube, but tailored for Kotlin best practices — and very extendable.



 Why Use Detekt in Android App Development?

Benefit Description
 Catch bugs early Find context leaks, unclosed resources, and anti-patterns
 Maintain clean code Auto-check complexity, style, naming
CI-ready Works in GitHub Actions, GitLab, Bitrise, etc.
Customizable Add or disable rules, write your own
Kotlin-first No Java compatibility hacks needed

 Step-by-Step Integration in Android Project

 Step 1: Apply Detekt Plugin

In your root build.gradle.kts or build.gradle:

plugins {
    id("io.gitlab.arturbosch.detekt") version "1.23.6"
}

Or use classpath in older plugin DSLs.

 Step 2: Add Configuration (Optional)

Generate a default configuration file:

./gradlew detektGenerateConfig

This creates:
config/detekt/detekt.yml
You can customize rules, thresholds, and disabled checks here.

 Step 3: Run Detekt

Use:

./gradlew detekt

Optional with config:

./gradlew detekt --config config/detekt/detekt.yml

It will output findings in the console and optionally HTML/MD/XML reports.


 Useful Detekt Rules (Leak & Jetpack Compose Focused)

1. UseApplicationContext

Flags dangerous use of Activity context that may lead to leaks.

class Repo(val context: Context) // 🚫 BAD

 Use context.applicationContext.


2. TooManyFunctions, LargeClass, LongMethod

Compose-friendly apps with many lambdas often need these enabled to track complexity.


3. UnsafeCallOnNullableType, CastToNullableType

Helps avoid unexpected crashes from nulls or unsafe casts.


4. ComplexCondition, NestedBlockDepth

Useful for detecting overly nested logic in state-handling Compose UIs.


5. MagicNumber, ForbiddenComment, MaxLineLength

Maintain clean and readable Compose files.


 Optional: Use Detekt with Compose + Custom Rules

You can even write custom Detekt rules to:

  • Detect misuse of remember or LaunchedEffect

  • Prevent ViewModel holding reference to Context

  • Flag mutable state misuse like:

var state by mutableStateOf(...) // without snapshot awareness? πŸ”₯ Flag it

You’d implement these with Detekt's Rule API.


 CI Integration Example (GitHub Actions)

- name: Run Detekt
  run: ./gradlew detekt

You can configure it to fail PRs on violation, ensuring team-wide quality.


 Best Practices When Using Detekt

Practice Benefit
 Customize detekt.yml Tailor rules to team/style guidelines
 Run in CI Prevent regression and enforce code health
 Use for Context Leak Rules Prevent common Android lifecycle bugs
 Track complexity & function size Useful for Compose UI layers
 Extend for custom Compose rules Detect architecture violations

 Output Formats

  • Console (default)

  • HTMLbuild/reports/detekt/detekt.html

  • XML – for tools like SonarQube

  • SARIF – for GitHub Code Scanning


 Summary

Feature Value
Kotlin-first Yes 
Jetpack Compose friendly  Can flag misuse and complexity
Leak prevention  Context, state misuse, null safety
Configurable Fully customizable rules
Extendable Supports custom rule sets
CI Ready Easy to integrate in pipelines

πŸ”— Useful Links


πŸ“’ Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! Please leave a comment below. I’d love to hear from you! πŸ‘‡

Happy coding! πŸ’»

Shipping High-Quality Android Code with Testing in Iterative Cycles (Kotlin + Jetpack Compose)

In modern Android development, building robust apps goes far beyond just writing code. It’s about delivering high-quality features in iterative cycles with the confidence that everything works as expected. This article walks you through a full feature development cycle in Android using Kotlin, Jetpack Compose, and modern testing practices.

We’ll build a simple feature: a button that fetches and displays user data. You'll learn how to:

  • Structure code using ViewModel and Repository

  • Write unit and UI tests

  • Integrate automated testing in CI/CD pipelines

Let’s dive in 

Full Cycle with Testing - Detailed Steps


Step 1: Set up your environment and dependencies

Before starting, ensure your project has the following dependencies in build.gradle (Module-level):

dependencies {
    implementation "androidx.compose.ui:ui:1.3.0"
    implementation "androidx.compose.material3:material3:1.0.0"
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.6.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
    testImplementation "junit:junit:4.13.2"
    testImplementation "org.mockito:mockito-core:4.0.0"
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:1.3.0"
    androidTestImplementation "androidx.test.ext:junit:1.1.5"
    androidTestImplementation "androidx.test.espresso:espresso-core:3.5.0"
}

Step 2: Implement the Feature

Let’s assume the feature involves a button that, when clicked, fetches user data from an API.

2.1: Create the User Data Model

data class User(val id: Int, val name: String)

2.2: Create the UserRepository to Fetch Data

class UserRepository {
    // Simulate network request with delay
    suspend fun fetchUserData(): User {
        delay(1000)  // Simulating network delay
        return User(id = 1, name = "John Doe")
    }
}

2.3: Create the UserViewModel to Expose Data

class UserViewModel(private val repository: UserRepository) : ViewModel() {
    private val _userData = MutableLiveData<User?>()
    val userData: LiveData<User?> get() = _userData

    fun fetchUser() {
        viewModelScope.launch {
            _userData.value = repository.fetchUserData()
        }
    }
}

2.4: Create the UserScreen Composable to Display Data

@Composable
fun UserScreen(viewModel: UserViewModel) {
    val user by viewModel.userData.observeAsState()
    Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
        Button(onClick = { viewModel.fetchUser() }) {
            Text("Fetch User")
        }
        user?.let {
            Text(text = "User: ${it.name}")
        } ?: Text(text = "No user fetched yet")
    }
}

Step 3: Write Unit Tests

3.1: Unit Test for UserRepository

Write a simple unit test to test that UserRepository correctly fetches user data.

@RunWith(MockitoJUnitRunner::class)
class UserRepositoryTest {
    private lateinit var repository: UserRepository

    @Before
    fun setup() {
        repository = UserRepository()
    }

    @Test
    fun testFetchUserData() = runBlocking {
        val result = repository.fetchUserData()
        assertEquals(1, result.id)
        assertEquals("John Doe", result.name)
    }
}

3.2: Unit Test for UserViewModel

Next, test that the UserViewModel correctly interacts with the repository and updates the UI state.

class UserViewModelTest {
    private lateinit var viewModel: UserViewModel
    private lateinit var repository: UserRepository

    @Before
    fun setup() {
        repository = mock(UserRepository::class.java)
        viewModel = UserViewModel(repository)
    }

    @Test
    fun testFetchUser() = runBlocking {
        val user = User(1, "John Doe")
        `when`(repository.fetchUserData()).thenReturn(user)

        viewModel.fetchUser()

        val value = viewModel.userData.getOrAwaitValue()  // Use LiveData testing extensions
        assertEquals(user, value)
    }
}

Step 4: Write UI Tests with Jetpack Compose

4.1: Write Compose UI Test

Use ComposeTestRule to test the UserScreen composable.

@get:Rule
val composeTestRule = createComposeRule()

@Test
fun testFetchUserButton_click() {
    val viewModel = UserViewModel(UserRepository())

    composeTestRule.setContent {
        UserScreen(viewModel)
    }

    // Assert that the UI initially shows the "No user fetched yet" text
    composeTestRule.onNodeWithText("No user fetched yet").assertIsDisplayed()

    // Simulate button click
    composeTestRule.onNodeWithText("Fetch User").performClick()

    // After clicking, assert that "User: John Doe" is displayed
    composeTestRule.onNodeWithText("User: John Doe").assertIsDisplayed()
}

4.2: Write Espresso Test for Hybrid UI (if needed)

In case you’re testing a hybrid UI (Jetpack Compose + XML Views), you can also use Espresso.

@Test
fun testFetchUserButton_click() {
    onView(withId(R.id.fetchUserButton)).perform(click())
    onView(withId(R.id.resultText)).check(matches(withText("User: John Doe")))
}

Step 5: Run All Tests in CI/CD

  • Set up GitHub Actions or Jenkins to automatically run the tests on every push to the repository.

Here’s an example configuration for GitHub Actions:

name: Android CI

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Set up JDK
        uses: actions/setup-java@v2
        with:
          java-version: '11'

      - name: Build and test
        run: ./gradlew build testDebugUnitTest connectedDebugAndroidTest

Step 6: Code Review and Refactor

With your code and tests in place:

  •  Refactor for better architecture

  •  Add new states like loading and error

  •  Add tests for edge cases

  •  Merge changes with confidence

  •  Release to staging/production


Step 7: Deploy to Staging or Production

After successful tests, deploy the feature to a staging environment or directly to production, depending on your CI/CD pipeline.


Key Takeaways:

  1. Iterative development: Implement small, testable features and enhance them with every iteration.

  2. Automate testing: Unit tests, UI tests, and integration tests should be automated and run on every code change.

  3. Focus on user behavior: Write tests that mimic real user behavior (e.g., pressing buttons and verifying UI changes).

  4. Continuous integration: Set up CI/CD pipelines to run tests automatically and ensure the stability of your app at all times.

By following this cycle, you ensure that the app is always in a deployable state, with tests proving that each feature works as expected.

Final Thoughts

Iterative development backed by strong testing practices ensures you can deliver robust Android features without fear of breaking the app. With tools like Jetpack Compose, JUnit, and CI/CD, it’s never been easier to ship confidently.

πŸ’‘ “The best code is not only written, it's verified and trusted by tests.”



πŸ“’ Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! 😊 please leave a comment below. I’d love to hear from you! πŸ‘‡

Happy coding! πŸ’»✨

How to Fix Android App Bugs Without Breaking Everything Else

When fixing bugs in an Android app project, it's crucial to not just patch the issue, but to ensure stability, performance, and maintainability of the app. Here's a structured list of key areas to address during bug fixing:


 1. Reproduce and Isolate the Bug

  • Reproduce the issue consistently in a local or QA environment.

  • Logcat analysis: Use Log.d, Log.e, Timber, etc., to check stack traces and contextual logs.

  • Crash reports: Utilize tools like Firebase Crashlytics, Sentry, or Bugsnag to identify the root cause.

  • Debug tools: Use Android Studio debugger, breakpoints, or Flipper for runtime inspection.


 2. Identify Root Cause (Not Just Symptoms)

  • Avoid surface-level fixes that mask the issue.

  • Trace through stack traces, thread state, and lifecycle behavior.

  • Use techniques like binary search debugging, rollback comparison, or git bisect.


 3. Check Affected Scope and Dependencies

  • Understand the scope: What modules/features are impacted?

  • Review dependencies (third-party libraries, APIs, database, sensors, etc.).

  • Check for side effects or hidden regressions in related components.


4. Fix Using Best Practices

  • Apply Kotlin null safety, immutability, lifecycle awareness, and coroutine exception handling.

  • Respect architecture (e.g., Clean Architecture, MVVM).

  • Avoid memory leaks (e.g., by cleaning up observers or references in onCleared() or onDestroy()).


5. Test the Fix Thoroughly

  • Unit test the logic.

  • UI/Instrumentation tests (e.g., using Espresso).

  • Edge cases: test on different devices, orientations, languages, and API levels.

  • Use mock data and real-world scenarios.

  • Automate via CI/CD if possible.


6. Code Review & PR Standards

  • Push changes to a feature or hotfix branch.

  • Follow team PR templates/checklists.

  • Include before/after behavior screenshots or videos (especially for UI bugs).

  • Peer review for readability, performance, and maintainability.


7. Update Logs, Metrics, and Documentation

  • Update CHANGELOG.md or release notes.

  • Add JIRA/Trello references and resolution notes.

  • If it's a backend-related issue, sync with backend devs.

  • If API contract changes, update API schema or versioning.


8. Deploy Carefully

  • Use staged rollout (e.g., Play Console’s percentage rollout).

  • Monitor logs and crash analytics post-deploy.

  • Add feature flags if needed for emergency disable.

9. Retrospective or Root Cause Analysis (RCA)

  • Log the root cause and learnings in a shared document.

  • Improve test coverage or monitoring based on the gap.

  • Share insights with the team in sprint retro or knowledge base.


Tools That Help:

Category Tool
Logging Timber, Logcat, Crashlytics
Debugging Android Studio, Flipper, LeakCanary
Monitoring Firebase Performance, Sentry
Testing JUnit, Espresso, MockK, Robolectric
CI/CD GitHub Actions, Bitrise, Jenkins
Issue Tracking Jira, Trello, Linear

Here’s a realistic example of a bug fix in an Android app, including the bug description, root cause, fix implementation, and testing strategy.


Example : App Crashes on Orientation Change While Loading Data


Bug Report

  • Title: App crashes when rotating screen during data loading on ProfileFragment.

  • Severity: High (crashes app)

  • Environment: Android 12, Pixel 5, API 31

  • Steps to Reproduce:

    1. Open the app and navigate to Profile tab.

    2. While the data is loading (loading spinner showing), rotate the screen.

    3. App crashes with IllegalStateException.


Crash Log

java.lang.IllegalStateException: ViewModel not attached to lifecycle yet
    at ProfileViewModel.getProfileData(ProfileViewModel.kt:45)

Root Cause

  • The ProfileFragment was trying to observe LiveData before the view was fully recreated after orientation change.

  • The data load was tied to the fragment’s onCreateView rather than viewLifecycleOwner.


Fix

Refactor LiveData observer to bind with viewLifecycleOwner instead of the fragment's lifecycle.

// Before (incorrect)
viewModel.profileLiveData.observe(this, Observer {
    // update UI
})

// After (correct)
viewModel.profileLiveData.observe(viewLifecycleOwner, Observer {
    // update UI
})

Additionally, use repeatOnLifecycle for Kotlin Flow in Compose or ViewModel coroutine collection:

lifecycleScope.launch {
    viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.profileFlow.collect {
            // Update UI
        }
    }
}

Testing Done

  • Rotated device multiple times during and after data load.

  • Verified no crashes on API 30, 31, 34.

  • Verified ViewModel data not lost.

  • Espresso UI test added for rotation.


PR Notes

πŸ“Œ Fixed crash on orientation change in ProfileFragment by using viewLifecycleOwner for LiveData observer. Added test for configuration change handling.
JIRA Ticket: APP-2931
Impact: Profile screen lifecycle handling.


Improvement

Added lifecycle-aware logging to catch future orientation-related issues:

Log.d("Lifecycle", "ProfileFragment state: ${lifecycle.currentState}")

πŸ“’ Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! 😊 please leave a comment below. I’d love to hear from you! πŸ‘‡

Happy coding! πŸ’»✨

Implementing an LRU Cache in Android using Kotlin and Jetpack Compose

In Android development, caching is a critical technique for storing data locally for quicker access, reducing network calls, and enhancing the user experience. One popular caching technique is the Least Recently Used (LRU) cache, which automatically evicts the least recently accessed data when the cache reaches its limit. This post explores how to implement an LRU cache in Android using Kotlin and Jetpack Compose.


What is an LRU Cache?

Least Recently Used (LRU) is a caching strategy that removes the least recently accessed items first when the cache exceeds its defined limit. It's optimal when you want to cache a limited amount of data, such as images, objects, or API responses, and ensure only frequently used items remain in memory.

Benefits:

  • Reduces memory footprint

  • Speeds up data retrieval

  • Avoids unnecessary API calls or file reads

  • Automatically manages cache eviction


Use Cases of LRU Cache in Android

Use Case Description
Image Caching Store bitmap images fetched from the network to avoid repeated downloads
Network Responses Save HTTP responses (e.g., user profile, dashboard data) to speed up load times
File or Object Caching Cache local files or data models in memory for quick reuse
Custom In-App Caching Temporary store for autocomplete suggestions, search history, etc.

 Implementing LRU Cache in Kotlin (Without External Libraries)

Step 1: Create an LRU Cache Manager

class LruCacheManager<K, V>(maxSize: Int) {
    private val cache = object : LruCache<K, V>(maxSize) {
        override fun sizeOf(key: K, value: V): Int {
            return 1 // Customize this if needed (e.g., for Bitmaps)
        }
    }

    fun put(key: K, value: V) {
        cache.put(key, value)
    }

    fun get(key: K): V? {
        return cache.get(key)
    }

    fun evictAll() {
        cache.evictAll()
    }
}

☝️ Note: This uses Android’s built-in LruCache<K, V> from android.util.LruCache.


Example: Caching User Profiles

Let’s say you’re loading user profiles from an API, and want to cache them in memory to avoid reloading them repeatedly.

Step 2: Define a simple data model

data class UserProfile(val id: Int, val name: String, val avatarUrl: String)

Step 3: Create a ViewModel using StateFlow and LruCache

class UserProfileViewModel : ViewModel() {
    private val cache = LruCacheManager<Int, UserProfile>(maxSize = 5)

    private val _userProfile = MutableStateFlow<UserProfile?>(null)
    val userProfile: StateFlow<UserProfile?> = _userProfile

    fun loadUserProfile(userId: Int) {
        cache.get(userId)?.let {
            _userProfile.value = it
            return
        }

        viewModelScope.launch {
            // Simulate network call
            delay(1000)
            val user = UserProfile(userId, "User $userId", "https://picsum.photos/200/200?random=$userId")
            cache.put(userId, user)
            _userProfile.value = user
        }
    }
}

Jetpack Compose UI

@Composable
fun UserProfileScreen(viewModel: UserProfileViewModel = viewModel()) {
    val profile by viewModel.userProfile.collectAsState()

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = { viewModel.loadUserProfile((1..10).random()) }) {
            Text("Load Random User")
        }

        Spacer(modifier = Modifier.height(20.dp))

        profile?.let {
            Text(text = it.name, style = MaterialTheme.typography.titleLarge)
            AsyncImage(
                model = it.avatarUrl,
                contentDescription = "Avatar",
                modifier = Modifier.size(120.dp).clip(CircleShape)
            )
        } ?: Text("No user loaded")
    }
}

Best Practices for Using LRU Cache

Tip Description
Use LruCache only for in-memory caching Do not use it for persistent or disk-based caching
Define a sensible maxSize Based on app usage pattern and available memory
For image caching, use Bitmap size as the unit Override sizeOf() method
Evict cache on memory warnings Use onTrimMemory() or onLowMemory() callbacks
Use libraries like Coil, Glide, or Picasso They offer built-in LRU support for image loading

πŸ”š Remember

The LRU caching mechanism is a simple yet powerful technique in Android development. It keeps your UI snappy and responsive by reducing network usage and data load time. While libraries like Glide manage LRU for images out of the box, creating your custom LRU cache gives you flexibility and control—especially when caching JSON responses or domain objects.

Pro Tip: Combine LruCache with StateFlow and Jetpack Compose for real-time UI updates and smoother UX.



#AndroidDevelopment #Kotlin #JetpackCompose #LRUCache #CachingInAndroid #StateFlow #PerformanceOptimization



πŸ“’ Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! 😊 please leave a comment below. I’d love to hear from you! πŸ‘‡

Happy coding! πŸ’»✨



Exploring Scope Functions in Kotlin Compose

Kotlin provides several powerful scope functions that make your code more readable and concise. These scope functions — let, run, apply, also, and with — are particularly useful when working with Kotlin's modern Android development framework, Jetpack Compose. 

Scope functions in Kotlin allow you to execute a block of code within the context of an object. Each of these functions has different characteristics and return values. They can be used for various purposes, like modifying an object, chaining function calls, or simplifying code readability.

1. let – Transform the Object and Return the Result

The let function executes a block of code on the object it is invoked on and returns the result of the block. It's often used when working with an object and returning a result without modifying the original object.

Syntax:

val result = object.let {
    // Do something with object
    "result"
}

Example in Compose: Suppose we want to handle an event in Jetpack Compose like a button click, where we only need to transform the result or pass it on to another function:

val buttonText = "Click me"
val result = buttonText.let {
    it.toUpperCase()
}

Text(text = result)  // Output: "CLICK ME"

In this example, the let function transforms buttonText to uppercase without modifying the original string.

2. run – Execute a Block and Return the Result

run is similar to let, but it is typically used when you want to execute a block of code and return a result. Unlike let, run doesn’t take the object as an argument — instead, it works within the object's context.

Syntax:

val result = object.run {
    // Do something with object
    "result"
}

Example in Compose: When creating a composable, you can use run to set up complex UI elements or operations:

val result = "Hello".run {
    val length = length
    "Length of text: $length"
}

Text(text = result)  // Output: "Length of text: 5"

Here, we used run to access properties and perform operations on a string. The function directly returns the result without modifying the object.

3. apply – Configure an Object and Return It

The apply function is used when you want to modify an object and return the modified object itself. It’s particularly useful for setting multiple properties on an object.

Syntax:

val modifiedObject = object.apply {
    // Modify object properties
}

Example in Compose: For instance, in Jetpack Compose, you can use apply when configuring a Modifier object to add multiple modifications:

val modifier = Modifier
    .padding(16.dp)
    .apply {
        background(Color.Blue)
        fillMaxSize()
    }

Box(modifier = modifier) {
    Text(text = "Hello World")
}

In this case, the apply function allows chaining multiple properties on the Modifier object and returns the same object after applying changes.

4. also – Perform an Action and Return Object

The also function is often used when you want to perform additional actions on an object but don’t want to change or return a new object. It’s often used for logging or debugging.

Syntax:

val objectWithAction = object.also {
    // Perform actions like logging
}

Example in Compose: Suppose you want to log a value when a user clicks a button in Compose:

val clickCount = remember { mutableStateOf(0) }

Button(onClick = {
    clickCount.value = clickCount.value.also {
        println("Button clicked: ${clickCount.value} times")
    } + 1
}) {
    Text("Click Me")
}

In this example, the also function is used to log the click count before updating the value of clickCount.

5. with – Execute a Block on an Object Without Returning It

The with function is used when you want to perform several actions on an object without modifying or returning it. It operates similarly to run, but unlike run, which operates in the context of the object, with requires the object to be passed explicitly.

Syntax:

with(object) {
    // Perform actions
}

Example in Compose: If you want to configure a composable’s properties, you can use with for better readability:

val modifier = with(Modifier) {
    padding(16.dp)
    background(Color.Green)
    fillMaxSize()
}

Box(modifier = modifier) {
    Text("Welcome to Compose!")
}

Here, with is used to apply multiple modifiers without repeatedly referencing the Modifier object.

Key Differences Between Scope Functions

  • let: Useful when you transform the object and return a result. The object is passed as an argument to the block.

  • run: This is similar to let, but the object is accessed directly within the block. It is helpful when returning a result after performing operations.

  • apply: Modifies the object and returns the object itself. Ideal for object configuration.

  • also: Similar to apply, but used primarily for performing side actions (like logging), while returning the original object.

  • with: Works like run, but requires the object to be passed explicitly and is used when you need to operate on an object without modifying it.

When to Use Each in Jetpack Compose

  • let: When you must transform or pass an object’s value.

  • run: When performing operations within the context of an object and returning the result.

  • apply: When you need to modify an object (like a Modifier) and return it after changes.

  • also: For performing additional actions (e.g., logging or debugging) without changing the object.

  • with: When you want to execute multiple operations on an object without modifying it.

Summary

Scope functions are essential to Kotlin’s functional programming style, offering a concise and readable way to work with objects. In Jetpack Compose, they help streamline UI development, manage states, and enhance overall code readability. Whether you’re configuring UI elements, performing transformations, or logging actions, scope functions can significantly reduce boilerplate and improve the efficiency of your Kotlin Compose code.

πŸ“’ Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! 😊 please leave a comment below. I’d love to hear from you! πŸ‘‡

Happy coding! πŸ’»✨

Migrate from KAPT to KSP in Android

In 2025, Android Studio LadyFrog has made it easier than ever to take advantage of the latest tools for Kotlin development. One such tool is Kotlin Symbol Processing (KSP), which provides a faster, more Kotlin-friendly alternative to Kotlin Annotation Processing Tool (KAPT). If you want to optimize your Android project, migrating from KAPT to KSP should be a priority. This migration can bring numerous benefits, such as improved build performance, better Kotlin feature integration, and a more streamlined development process. 


Why Migrate from KAPT to KSP?

KAPT has been the standard annotation processing tool for Kotlin for years. It serves its purpose well, but there are several reasons to migrate to KSP, especially in Android development.

1. Faster Build Performance

KAPT processes Kotlin code by first converting it to Java before running the annotation processor. This additional conversion step increases build times, especially in large projects. KSP, on the other hand, operates directly on Kotlin code, eliminating the need for this conversion and significantly reducing build times.

2. Better Kotlin-Specific Feature Support

While KAPT works fine with Kotlin, it was originally designed for Java and doesn't always handle Kotlin’s language features efficiently. KSP, explicitly designed for Kotlin, integrates seamlessly with Kotlin’s advanced features like data classes, sealed classes, and extension functions. KSP is thus more flexible and allows you to take full advantage of Kotlin's features.

3. Multiplatform Compatibility

KSP supports Kotlin Multiplatform (KMP), making generating code that works across platforms like Android and iOS is easier. If you're building a multiplatform project, migrating to KSP is the way forward as it will allow for better code sharing between platforms.

4. Simplified Annotation Processing

KSP uses a more straightforward API, making it easier to understand and use for code generation. Developers will find KSP easier to debug and work with, improving the overall development experience.

5. Memory Efficiency

KAPT can be memory-intensive because of its Java conversion step. KSP is designed to be lighter and more memory-efficient, which is particularly useful for large projects with extensive annotation processing.

Benefits of Migrating to KSP

Migrating to KSP offers several benefits:

  • Improved build times: Faster annotation processing leads to quicker builds, enhancing development speed.

  • Enhanced Kotlin feature support: KSP is built to handle Kotlin features natively, allowing you to leverage Kotlin's full potential in your code generation.

  • Cleaner, simpler tooling: KSP simplifies the code generation process and makes integrating with your Android development workflow easier.

  • Better multiplatform support: KSP works well with Kotlin Multiplatform, making it easier to share code across different platforms.

Now that you know why migrating is essential, let's review the steps required to make this migration happen in Android Studio LadyFrog.

How to Migrate from KAPT to KSP in Android Studio LadyFrog (2025)

Migrating from KAPT to KSP is a straightforward process. Here are the steps to follow:

Step 1: Set Up KSP in build.gradle

In Android Studio LadyFrog, the configuration to use KSP is simple and clear. The first step is to add the KSP plugin and update your build.gradle files accordingly.

Project-Level build.gradle

In the project-level build.gradle, add the classpath for KSP:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        // Add the KSP plugin classpath
        classpath "com.google.devtools.ksp:symbol-processing-api:1.0.0"  // Update as per latest version
    }
}

App-Level build.gradle

In the app-level build.gradle, replace the KAPT plugin with KSP and update your dependencies. Here’s how you can do it:

apply plugin: 'com.google.devtools.ksp'

dependencies {
    // Replace KAPT with KSP for code generation libraries
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    ksp 'com.squareup.retrofit2:retrofit-ksp:2.9.0'  // Retrofit with KSP support

    // For Room, Dagger, or other annotation processors that support KSP
    ksp 'androidx.room:room-compiler:2.3.0'  // Room with KSP
    ksp 'com.google.dagger:dagger-compiler:2.35'  // Dagger with KSP
}

Step 2: Remove KAPT Plugin and Dependencies

Once you add KSP to your project, you need to remove KAPT from your build.gradle configuration. This includes removing the KAPT plugin and any dependencies associated with KAPT.

// Remove the KAPT plugin
apply plugin: 'kotlin-kapt'

// Remove KAPT dependencies
dependencies {
    // Remove kapt dependencies like
    // kapt 'com.squareup.retrofit2:retrofit-compiler:2.9.0'
}

Step 3: Update Annotation Processors for KSP Compatibility

For most annotation processors, like Retrofit, Dagger, and Room, you’ll need to update their dependencies to versions that support KSP. The syntax in your code doesn’t change—only the dependencies in build.gradle need to be updated.

For example, if you were using Retrofit with KAPT before:

kapt 'com.squareup.retrofit2:retrofit-compiler:2.9.0'

Now, use the KSP version:

ksp 'com.squareup.retrofit2:retrofit-ksp:2.9.0'

Step 4: Clean and Rebuild the Project

Once you have updated your dependencies and removed KAPT from your project, cleaning and rebuilding the project is essential to ensure that everything is now using KSP for annotation processing.

./gradlew clean build

This will remove the old KAPT-generated files and rebuild your project with KSP, optimizing the code generation process.

Example: Migrating Retrofit from KAPT to KSP

Let’s walk through an example where we migrate a Retrofit-based API service from KAPT to KSP.

Old Setup (with KAPT)

Before migration, your build.gradle file would look like this:

// build.gradle (App-Level)
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    kapt 'com.squareup.retrofit2:retrofit-compiler:2.9.0'  // Retrofit with KAPT
}

Your API service interface might look like this:

interface ApiService {
    @GET("users/{user}/repos")
    fun getRepos(@Path("user") user: String): Call<List<Repo>>
}

New Setup (with KSP)

After migrating to KSP, your build.gradle file will now look like this:

// build.gradle (App-Level)
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    ksp 'com.squareup.retrofit2:retrofit-ksp:2.9.0'  // Retrofit with KSP
}

Your ApiService interface remains the same, and the Retrofit library now uses KSP for annotation processing. There's no need to modify the code itself—only the dependencies in the build.gradle file need to be updated.

Step 5: Verify the Migration

After the migration is complete, make sure everything works as expected. Run your tests and verify that the generated code works correctly with KSP. Ensure all annotation processors function as expected and code generation is happening without issues.

Summary

Migrating from KAPT to KSP in Android Kotlin projects is a crucial step for optimizing performance and embracing Kotlin-specific features. By following the steps outlined in this article, you can easily migrate your Android project to KSP using Android Studio LadyFrog (2025). The migration will lead to faster build times, better Kotlin support, and improved development experience.

As the Android ecosystem evolves, migrating to KSP ensures that your project stays up-to-date with the latest tooling, allowing you to build high-performance, scalable apps with minimal hassle.

Happy coding!

Jetpack Compose Memory Issues: Causes, Impact, and Best Solutions

Memory performance is crucial to Android app development, especially when using Jetpack Compose. Inefficient memory management can lead to high memory usage, performance bottlenecks, and even app crashes due to OutOfMemoryError. In this article, we’ll explore the key moments when memory performance issues occur in Jetpack Compose, their root causes, and practical solutions to optimize memory usage.


When Do Memory Performance Issues Occur?

1. Unnecessary Recompositions

Jetpack Compose follows a declarative UI paradigm, where the UI updates when the state changes. However, inefficient recompositions can increase memory usage.

  • Occurs When:

    • misusing mutable states.
    • Not specifying keys in lists.
    • Using remember and rememberSaveable improperly.
  • Example of Bad Practice:

    @Composable
    fun Counter() {
        var count by remember { mutableStateOf(0) }
        Text(text = "Count: $count")
        Button(onClick = { count++ }) {
            Text("Increase")
        }
    }
    

    Here, every button click triggers a recomposition of the entire function.

  • Solution: Use remember Correctly

    @Composable
    fun Counter() {
        var count by remember { mutableStateOf(0) }
        Column {
            Text(text = "Count: $count")
            Button(onClick = { count++ }) {
                Text("Increase")
            }
        }
    }
    

    Now, only Text inside the Column is recommended when the count changes.


2. Large Image and Resource Loading

Mishandling images in Jetpack Compose can lead to excessive memory consumption.

  • Occurs When:

    • Loading high-resolution images without downscaling.
    • Keeping unnecessary image references in memory.
  • Example of Inefficient Image Handling:

    Image(
        painter = painterResource(id = R.drawable.large_image),
        contentDescription = "Large Image",
        modifier = Modifier.fillMaxSize()
    )
    
  • Solution: Use coil for Efficient Image Loading

    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data("https://example.com/large_image.jpg")
            .memoryCacheKey("large_image")
            .crossfade(true)
            .build(),
        contentDescription = "Large Image",
        modifier = Modifier.fillMaxSize()
    )
    

    Why? Coil automatically caches and optimizes image loading, reducing memory footprint.


3. Holding References to Large Objects

If an object is stored persistently in memory without proper cleanup, it can lead to memory leaks.

  • Occurs When:

    • Using remember without DisposableEffect or LaunchedEffect.
    • Keeping references to Activity or Context in composables.
  • Example of Memory Leak:

    val context = LocalContext.current
    val activity = context as Activity // Leaking the activity reference
    
  • Solution: Use Weak References

    @Composable
    fun SafeContextUsage() {
        val context = LocalContext.current.applicationContext // Avoid holding activity reference
    }
    

4. Misusing Coroutines in Jetpack Compose

Misusing coroutines can cause unnecessary memory consumption.

  • Occurs When:

    • Launching long-running coroutines in recomposing composables.
    • Forgetting to cancel coroutines.
  • Bad Practice (Coroutine Leak):

    @Composable
    fun FetchData() {
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            // API call
        }
    }
    

    Here, a new coroutine scope is created every time the function recomposes.

  • Solution: Use LaunchedEffect

    @Composable
    fun FetchData() {
        LaunchedEffect(Unit) {
            // API call runs only once
        }
    }
    

    This ensures the coroutine starts only once per composition.


5. Using Large Lists Without Optimization

Rendering large lists without optimizations can cause high memory usage and laggy performance.

  • Occurs When:

    • Not using LazyColumn or LazyRow.
    • Keeping a large dataset in memory.
  • Bad Practice (Non-Optimized List):

    Column {
        items.forEach { item ->
            Text(text = item.name)
        }
    }
    

    This loads all items at once, increasing memory usage.

  • Solution: Use LazyColumn with Keys

    LazyColumn {
        items(items, key = { it.id }) { item ->
            Text(text = item.name)
        }
    }
    

    Why? LazyColumn only renders visible items, reducing memory usage.


Summary

Memory performance in Jetpack Compose can be impacted by improper state management, excessive recompositions, large object references, inefficient coroutine usage, and unoptimized lists. You can ensure a smooth and memory-efficient Android app by following best practices like using remember correctly, optimizing image loading, avoiding memory leaks, managing coroutines properly, and leveraging LazyColumn.

By proactively handling these issues, your app will perform better and offer a seamless user experience with optimal resource utilization.


Thanks for reading! I'd love to know what you think about the article. Did it resonate with you?  Any suggestions for improvement? I’m always open to hearing your feedback so that I can improve my posts! πŸ‘‡. Happy coding! πŸ’»

Bit Manipulation - Finding the missing number in a sequence in Kotlin


Problem Statement:

You are given an array containing n distinct numbers from 0 to n. Exactly one number in this range is missing from the array. You must find this missing number using bit manipulation techniques.

Example:

Input: [3, 0, 1]
Output: 2

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Explanation (using XOR):

A very efficient way to solve this using bit manipulation is to leverage XOR (^), which has these properties:

  • a ^ a = 0 (XOR of a number with itself is zero)
  • a ^ 0 = a (XOR of a number with zero is itself)
  • XOR is commutative and associative

Therefore, if we XOR all the indices and all the numbers, every number present will cancel out, leaving the missing number.


Implementation in Kotlin:

fun missingNumber(nums: IntArray): Int {
    var xor = nums.size // start with n, since array is from 0 to n
    for (i in nums.indices) {
        xor = xor xor i xor nums[i]
    }
    return xor
}

fun main() {
    println(missingNumber(intArrayOf(3, 0, 1))) // Output: 2
    println(missingNumber(intArrayOf(9,6,4,2,3,5,7,0,1))) // Output: 8
    println(missingNumber(intArrayOf(0,1))) // Output: 2
}

Complexity:

  • Time Complexity: O(n) (Iterates through the array once)
  • Space Complexity: O(1) (No extra space used)


Thanks for reading! πŸŽ‰ I'd love to know what you think about the article. Did it resonate with you? πŸ’­ Any suggestions for improvement? I’m always open to hearing your feedback to improve my posts! πŸ‘‡πŸš€. Happy coding! πŸ’»✨

Coroutines, RxJava, or Traditional Approach: Which is Better for Android Kotlin Compose?

When building Android applications, managing background tasks, handling asynchronous operations, and managing UI state can be a complex and error-prone task. Over the years, Android developers have adopted various approaches to handle these challenges. Today, we will dive into three prominent ways of handling concurrency and state management in Android using Kotlin and Jetpack Compose:

Each approach has strengths and weaknesses, and understanding when and why to use them will help you choose the right tool for your application.

1. Coroutines: The Modern Solution

What Are Coroutines?

Coroutines are Kotlin's built-in solution for handling asynchronous tasks more efficiently and readably. A coroutine is a lightweight thread that can be paused and resumed, making it ideal for handling asynchronous programming without blocking threads.

Coroutines are built into Kotlin and integrate well with Jetpack Compose. They allow developers to write asynchronous code sequentially, improving readability and maintainability. You can use Kotlin’s suspend functions to handle asynchronous operations, and Flow for reactive streams.

Why Use Coroutines?

  • Simplicity: The syntax is concise, and the code flows sequentially. It’s easier to read and manage, especially when combined with Kotlin’s suspend functions and Flow.
  • Efficiency: Coroutines are much more lightweight than threads. They can scale efficiently with minimal overhead, making them ideal for background operations in Android apps.
  • Built for Android: Coroutines, with official Android support and integrations like ViewModel, LiveData, and Room, work seamlessly with Jetpack Compose and other Android Jetpack components.
  • Integration with Jetpack Compose: Coroutines fit naturally with Jetpack Compose, allowing you to perform background tasks and update the UI without complex threading or lifecycle management.

Example: Using Coroutines in Jetpack Compose

@Composable
fun UserDataScreen() {
    val userData = remember { mutableStateOf("") }
    
    // Launching a coroutine for background work
    LaunchedEffect(Unit) {
        userData.value = getUserDataFromApi() // Suspend function
    }
    
    Text(text = userData.value)
}

suspend fun getUserDataFromApi(): String {
    delay(1000) // Simulate network call
    return "User Data"
}

When to Use Coroutines:

  • For modern Android development where simplicity, performance, and integration with Jetpack Compose are priorities.
  • When handling long-running background tasks or managing UI updates without blocking the main thread.

2. RxJava: The Reactive Approach

What Is RxJava?

RxJava is a popular library for reactively handling asynchronous programming. It is built around the concept of observable streams that emit values over time. RxJava uses concepts like Observable, Single, and Flowable to deal with data streams and asynchronous operations.

While Coroutines have become more popular, RxJava is still widely used, particularly in legacy applications or projects needing complex event-driven architectures.

Why Use RxJava?

  • Reactive Programming: RxJava is built around the principles of reactive programming. It’s ideal for scenarios where you must observe and react to data streams, such as network responses, user input, or sensor data.
  • Flexibility: With a vast set of operators, RxJava provides fine-grained control over data streams. You can combine, filter, merge, and transform streams.
  • Mature Ecosystem: RxJava has been around for a long time and has a strong ecosystem and community. It is well-documented and used in a wide variety of applications.

Example: Using RxJava in Jetpack Compose

@Composable
fun UserDataScreen() {
    val userData = remember { mutableStateOf("") }

    val disposable = Observable.fromCallable { getUserDataFromApi() }
        .subscribeOn(Schedulers.io()) // Run on background thread
        .observeOn(AndroidSchedulers.mainThread()) // Observe on UI thread
        .subscribe { data -> 
            userData.value = data
        }
    
    Text(text = userData.value)
}

fun getUserDataFromApi(): String {
    Thread.sleep(1000) // Simulate network call
    return "User Data"
}

When to Use RxJava:

  • For applications needing advanced stream manipulation, especially in complex asynchronous events.
  • When working with an existing codebase that already uses RxJava, or when you require extensive handling of multiple data streams.

3. The Traditional Approach (Callbacks, AsyncTasks)

What Is the Traditional Approach?

Before Coroutines and RxJava, Android developers used traditional ways like AsyncTask, Handler, and Callbacks to handle background work. While this approach is still used in some cases, it is generally considered outdated and prone to issues, especially in complex apps.

  • AsyncTask: Handles background tasks and post-execution UI updates.
  • Callbacks: Functions passed as parameters to be executed asynchronously.
  • Handler: Post messages or tasks to a thread’s message queue.

Why Avoid the Traditional Approach?

  • Callback Hell: Callbacks often result in nested functions, making the code harder to read, maintain, and debug. This is commonly referred to as “callback hell.”
  • Limited Flexibility: Traditional methods like AsyncTask don’t provide the flexibility and power of RxJava or Coroutines when dealing with complex data streams or managing concurrency.
  • Lifecycle Issues: Traditional approaches to managing the lifecycle of background tasks in Android can be error-prone, especially when handling configuration changes like device rotations.

Example: Using AsyncTask (Outdated)

class UserDataTask : AsyncTask<Void, Void, String>() {
    override fun doInBackground(vararg params: Void?): String {
        // Simulate network call
        Thread.sleep(1000)
        return "User Data"
    }
    
    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        // Update UI
        userData.value = result
    }
}

When to Avoid the Traditional Approach:

  • When building modern Android apps using Kotlin, Jetpack Compose, and requiring efficient, readable, and maintainable code.
  • For complex asynchronous operations that involve multiple threads, streams, or require lifecycle-aware handling.

Conclusion: Which One to Choose?

  • Coroutines are the preferred choice for modern Android development with Kotlin and Jetpack Compose. They are lightweight, concise, and integrate well with the Android lifecycle.
  • RxJava is excellent if you're working with complex data streams, need advanced operators for manipulating streams, or deal with a legacy codebase that already uses RxJava.
  • The traditional approach is best avoided for modern Android development due to its limitations in handling asynchronous tasks, complex UI updates, and maintaining clean code.

Coroutines should be the preferred solution for most Android apps built with Jetpack Compose. They provide simplicity, performance, and compatibility with modern Android development practices.

Thanks for reading! πŸŽ‰ I'd love to know what you think about the article. Did it resonate with you? πŸ’­ Any suggestions for improvement? I’m always open to hearing your feedback to improve my posts! πŸ‘‡πŸš€. Happy coding! πŸ’»✨


MVVM vs MVI vs MVP: Which Architecture Fits Your Android Kotlin Compose Project?

When developing Android apps using Kotlin and Jetpack Compose, the architecture you choose should align with your application's needs, scalability, and maintainability. Let's explore the best architecture and discuss other alternatives with examples to help you make the best decision.

1. MVVM (Model-View-ViewModel) Architecture

Overview:

MVVM is the most commonly recommended architecture for Android apps using Jetpack Compose. It works seamlessly with Compose’s declarative UI structure and supports unidirectional data flow.

  • Model: Represents the data and business logic (e.g., network requests, database calls, etc.).
  • View: Composed of composable functions in Jetpack Compose. It displays the UI and reacts to state changes.
  • ViewModel: Holds UI-related state and business logic. It is lifecycle-aware and acts as a bridge between the View and Model.

How MVVM Works:

  • The View is responsible for presenting data using Compose. It observes the state exposed by the ViewModel via StateFlow or LiveData.
  • The ViewModel holds and processes the data and updates the state in response to user actions or external data changes.
  • The Model handles data fetching and business logic and communicates with repositories or data sources.

Benefits:

  • Separation of concerns: The View and Model are decoupled, making the app easier to maintain.
  • Reactivity: With Compose's state-driven UI, the View updates automatically when data changes in the ViewModel.
  • Scalability: MVVM works well for larger, complex apps.

Example:

// ViewModel
class MyViewModel : ViewModel() {
    private val _state = MutableStateFlow(MyState())
    val state: StateFlow<MyState> get() = _state

    fun fetchData() {
        // Simulate network request
        _state.value = _state.value.copy(data = "Fetched Data")
    }
}

// Composable View
@Composable
fun MyScreen(viewModel: MyViewModel = viewModel()) {
    val state by viewModel.state.collectAsState()

    Column {
        Text(text = state.data)
        Button(onClick = { viewModel.fetchData() }) {
            Text("Fetch Data")
        }
    }
}

Best For:

  • Real-time applications (e.g., chat apps, social media, etc.)
  • Apps with dynamic and complex UI requiring frequent backend updates.
  • Enterprise-level applications where clear separation of concerns and scalability are required.

2. MVI (Model-View-Intent) Architecture

Overview:

MVI focuses on unidirectional data flow and immutable state. It's more reactive than MVVM and ensures that the View always displays the latest state.

  • Model: Represents the application’s state, typically immutable.
  • View: Displays the UI and reacts to state changes.
  • Intent: Represents the actions that the View triggers (e.g., button clicks, user input).

How MVI Works:

  • The View sends Intents (user actions) to the Presenter (or ViewModel).
  • The Presenter updates the Model (state) based on these actions and then triggers a state change.
  • The View observes the state and re-renders itself accordingly.

Benefits:

  • Unidirectional data flow: The state is always predictable as changes propagate in one direction.
  • Immutable state: Reduces bugs associated with mutable state and ensures UI consistency.
  • Reactive: Well-suited for applications with frequent UI updates based on state changes.

Example:

// MVI - State, ViewModel
data class MyState(val data: String = "")

class MyViewModel : ViewModel() {
    private val _state = MutableStateFlow(MyState())
    val state: StateFlow<MyState> get() = _state

    fun processIntent(intent: MyIntent) {
        when (intent) {
            is MyIntent.FetchData -> {
                _state.value = MyState("Fetched Data")
            }
        }
    }
}

// Composable View
@Composable
fun MyScreen(viewModel: MyViewModel = viewModel()) {
    val state by viewModel.state.collectAsState()

    Column {
        Text(text = state.data)
        Button(onClick = { viewModel.processIntent(MyIntent.FetchData) }) {
            Text("Fetch Data")
        }
    }
}

Best For:

  • Complex UI interactions: Apps with multiple states and actions that must be tightly controlled.
  • Real-time data-driven apps where state changes must be captured and handled immutably.
  • Apps that require a highly reactive UI, such as games or media streaming apps.

3. MVP (Model-View-Presenter) Architecture

Overview:

MVP is a simpler architecture often used in legacy apps. In MVP, the Presenter controls the logic and updates the View, which is passive and only responsible for displaying data.

  • Model: Represents the data and business logic.
  • View: Displays UI and delegates user interactions to the Presenter.
  • Presenter: Acts as a middleman, processing user input and updating the View.

How MVP Works:

  • The View delegates all user actions (clicks, input, etc.) to the Presenter.
  • The Presenter fetches data from the Model and updates the View accordingly.

Benefits:

  • Simple and easy to implement for small applications.
  • Decouples UI logic from the data layer.

Example:

// MVP - Presenter
interface MyView {
    fun showData(data: String)
}

class MyPresenter(private val view: MyView) {
    fun fetchData() {
        // Simulate fetching data
        view.showData("Fetched Data")
    }
}

// Composable View
@Composable
fun MyScreen(view: MyView) {
    val presenter = remember { MyPresenter(view) }

    Column {
        Button(onClick = { presenter.fetchData() }) {
            Text("Fetch Data")
        }
    }
}

class MyViewImpl : MyView {
    override fun showData(data: String) {
        println("Data: $data")
    }
}

Best For:

  • Simple apps with minimal business logic.
  • Legacy projects that already follow the MVP pattern.
  • Applications with simple user interactions that don’t require complex state management.

Conclusion: Which Architecture to Choose?

Architecture Strengths Best For Example Use Cases
MVVM Seamless integration with Jetpack ComposeClear separation of concernsScalable and testable Large, complex appsReal-time appsTeam-based projects E-commerce apps, banking apps, social apps
MVI Immutable stateUnidirectional data flowReactive UI Highly interactive appsReal-time dataComplex state management Messaging apps, live score apps, media apps
MVP Simple to implementGood for small appsEasy to test Small appsLegacy appsSimple UI interactions Note-taking apps, simple tools, legacy apps

Best Recommendation:

  • MVVM is generally the best architecture for most Android Kotlin Compose apps due to its scalability, maintainability, and seamless integration with Compose.
  • MVI is ideal for apps that require complex state management and reactive UI updates.
  • MVP is still useful for simple apps or projects that already follow MVP.

Thanks for reading! πŸŽ‰ I'd love to know what you think about the article. Did it resonate with you? πŸ’­ Any suggestions for improvement? I’m always open to hearing your feedback to improve my posts! πŸ‘‡πŸš€. Happy coding! πŸ’»✨