ProAndroidDev
The latest posts from Android Professionals and Google Developer Experts.
proandroiddev.comThe latest posts from Android Professionals and Google Developer Experts.
proandroiddev.comclass OldViewModel { // 1. The private mutable state private val _uiState = MutableStateFlow(UiState()) // 2. The public read-only state val uiState: StateFlow<UiState> = _uiState.asStateFlow() } This is tedious to write, but it provides a strict architectural guarantee. When you call .asStateFlow(), Kotlin does not just change the type; it creates a brand new wrapper object in memory (ReadonlyStateFlow). While this physical barrier is fantastic for safety, it does mean you are incurring a minor memory allocation overhead by creating a secondary wrapper object for every exposed state. ### The New Way: Upcasting Explicit Backing Fields allow you to merge these two properties into one concise declaration, bypassing that extra memory allocation entirely: class NewViewModel { val uiState: StateFlow<UiState> field = MutableStateFlow(UiState()) } Inside your class, the Kotlin compiler smart-casts the field so you can mutate it internally. Outside the class, the compiler restricts callers to the read-only StateFlow interface. It looks incredibly clean and saves an allocation, but it introduces a subtle architectural vulnerability. ### The Downcast Trap Because Explicit Backing Fields do not create a wrapper object, the underlying object in memory is still a MutableStateFlow. You are relying entirely on the compiler’s upcasting to hide the mutability. If a consumer outside of your class decides to aggressively downcast your state, the behaviors of these two approaches are drastically different: // Scenario A: The Old Way // ❌ Fails with ClassCastException at runtime (oldViewModel.uiState as MutableStateFlow).value = BadState() // Scenario B: The New Way // ⚠️ Silently succeeds and corrupts your internal state (newViewModel.uiState as MutableStateFlow).value = BadState() With the old way, the ClassCastException acts as a physical barrier preventing architectural violations. With Explicit Backing Fields, a rogue downcast will succeed, and your internal state can be silently mutated from the outside, bypassing your business logic entirely. ### The Pragmatic Reality: Is it a dealbreaker? Is this a reason to avoid Explicit Backing Fields? For most application development teams, no. We already accept this exact same tradeoff with standard Kotlin collections. Exposing a List that is secretly a MutableList under the hood is a standard practice, and it relies on the exact same upcasting mechanism. You should not design your internal application architecture around the assumption that your teammates are actively writing malicious downcasts to bypass your interfaces. That is what Code Reviews and Static Analysis tools (like Detekt or SonarQube) are for. The Exception: If you are writing a closed-source SDK or a public library where you cannot trust the consuming application, you should absolutely stick to defensive wrappers like .asStateFlow(). In a public API surface, physical boundaries matter more than saving a micro-allocation. Are you planning to adopt Explicit Backing Fields in your codebase, or do you prefer the strict wrapper protection of the old approach? Let me know your thoughts in the comments! --- The “Downcast Trap” in Kotlin’s Explicit Backing Fields was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.kotlin { @OptIn(ExperimentalWasmDsl::class) wasmJs { browser() binaries.executable() } sourceSets { wasmJsMain.dependencies { implementation("org.jetbrains.kotlinx:kotlinx-browser:0.3") implementation(npm("firebase", "12.18.0")) } } } One thing to watch out for: if your project also has a js target using the Firebase-Kotlin-SDK, those dependencies need to move from commonMain to jsMain, because they won't resolve for Wasm. Now to the essential part. If you read my Google Sign-in article for JS, you might remember externals.auth.kt, the file in the GitLive library bridging the gap between Kotlin and external JavaScript modules. This time we write that bridge ourselves. It's surprisingly little code. Two files, one per Firebase module: @file:JsModule("firebase/app") package com.kmp.webauth.externals external interface FirebaseApp : JsAny external fun initializeApp(options: JsAny): FirebaseApp @file:JsModule("firebase/auth") package com.kmp.webauth.externals import kotlin.js.Promise external interface Auth : JsAny external interface User : JsAny { val uid: String val displayName: String? val email: String? } external interface UserCredential : JsAny { val user: User } external class GoogleAuthProvider() : JsAny external fun getAuth(app: FirebaseApp): Auth external fun signInWithPopup(auth: Auth, provider: GoogleAuthProvider): Promise<UserCredential> That’s the whole “SDK”. The @file:JsModule annotation tells the compiler these declarations come from the firebase/auth npm module, and webpack takes care of the rest. Notice that everything extends JsAny. In Kotlin/Wasm, JavaScript values live on the other side of a strict boundary, and JsAny is your passport across it. Next, initialization. In Kotlin/JS we’d just throw together a json() or use dynamic. Wasm has neither. The way to build a plain JS object is a js() function with an object literal: private fun firebaseOptions( apiKey: String, authDomain: String, projectId: String, appId: String, ): JsAny = js("({ apiKey: apiKey, authDomain: authDomain, projectId: projectId, appId: appId })") val firebaseAuth: Auth by lazy { val app = initializeApp( firebaseOptions( apiKey = "yourApiKey", authDomain = "your-project.firebaseapp.com", projectId = "your-project", appId = "yourAppId", ) ) getAuth(app) } The values come from the same place as always: Firebase project -> Settings -> Web application -> firebaseConfig. And finally, the sign-in function itself. If you’ve read the JS articles this will look very familiar: fun signInWithGoogle( onSuccess: (displayName: String) -> Unit, onFailure: (message: String) -> Unit, ) { signInWithPopup(firebaseAuth, GoogleAuthProvider()) .then { credential -> onSuccess(credential.user.displayName ?: credential.user.email ?: credential.user.uid) null } .catch { error -> onFailure(messageOf(error)) null } } private fun messageOf(error: JsAny?): String = js("String((error && error.message) || error)") Two Wasm quirks here. First, the null at the end of each lambda: Promise callbacks must return a JsAny?, and Unit doesn't qualify, so we hand back null explicitly. Second, the error arriving in catch is a JsAny, not a Throwable, so extracting the message goes through another tiny js() helper. If you’re sharing UI between targets, wrap it in an expect fun signInWithGoogle(...) in commonMain. The Wasm actual is the function above, and the JS actual can keep delegating to the Firebase-Kotlin-SDK. Call it from any composable button and voilà ! One last tip before you test: Safari blocks the popup by default, and Firebase’s signInWithRedirect fallback doesn't play nicely with Safari's tracking prevention either. Test in Chrome first, then decide how much you care about Safari. Big shoutout to GitLive for the Firebase-Kotlin-SDK, their externals files were the blueprint for the declarations above. And if you'd like a guide for another provider on Wasm, drop a comment below and I'll make some time to create one for you! --- Kotlin / Wasm — Auth part 1: Google Sign in was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.API request ↓ Request fails ↓ Use default The problem is that the API does not stay unchanged. A configuration value can change. A new field can be introduced. A server-side behavior can evolve. The application itself can also change the way it interprets that data. Now there are effectively two sources of truth: API | | evolves ↓ Latest response Application | | evolves independently ↓ Hard-coded default Someone now has to remember to update the fallback whenever the API changes. That is where this approach starts to become unreliable. Someone will eventually forget. A new API case may not be represented in the fallback. A value may technically still be valid but no longer make sense for the current application version. Eventually, a failure can turn into something worse: API response ↓ Missing / unexpected case ↓ Fallback value ↓ Invalid state ↓ Bug or crash So I started thinking about a different question: > What if the default did not have to be manually maintained at all? ### Turning the API Response into a Fallback For certain types of APIs, we can use the build process to fetch the latest response and package it with the application. Instead of: default = manually maintained value we can make it: default = latest known valid API response The build process becomes: Production release ↓ Fetch API response ↓ Validate response ↓ Store as application resource ↓ Package with application At runtime, the application can then use that packaged snapshot when the live API does not provide a usable response: API request ↓ Success ───────────────→ Use live response │ ↓ Failure ↓ Use packaged snapshot The important part is where the fallback comes from. It is no longer a value that someone manually wrote months ago. It is a snapshot of real data that the API provided when the application was built. If the application is released every week or every couple of weeks, each production release can carry a relatively fresh snapshot. The snapshot is still stale compared with the live API, but it is at least recent and derived from the actual source of truth. ### Generating the Snapshot with Gradle The implementation can be surprisingly small. import java.net.URI tasks.register("refreshConfigDefaults") { val configDefaultsFile = layout.projectDirectory .file("src/commonMain/composeResources/files/config_defaults.json") .asFile doLast { val response = URI("https://dummy.host/api/v1/config") .toURL() .readText() // Validate before writing - a 200 response is not the same as a usable one. val isValid = validateConfigResponse(response) require(isValid) { "Config response failed validation, refusing to overwrite existing snapshot" } configDefaultsFile.parentFile?.mkdirs() if (!configDefaultsFile.exists()) { configDefaultsFile.createNewFile() } configDefaultsFile.writeText(response) } } fun validateConfigResponse(response: String): Boolean { // Parse into your expected data class and confirm required // fields are present. Return false (or throw) on anything // that would leave the application in an unusable state. return response.isNotBlank() } The task locates the resource file, fetches the API response, validates it, creates the directory and file when necessary, and only then writes the response into it. That file is then packaged into the application and becomes available as a fallback at runtime. The task itself is simple. The interesting part is the idea behind it: the build process is generating the fallback from the same source that normally supplies the live data. ### Refresh the Snapshot During Production Builds I would not make this task part of every build. A normal debug build, unit test, or development task should not unexpectedly make a network request simply to refresh fallback data. Instead, the refresh should be tied to the production release path. For example: tasks.named("assembleRelease") { dependsOn("refreshConfigDefaults") } This does mean a release build now hard-depends on that endpoint being reachable at build time. If the endpoint is unavailable, the release is blocked until the problem is resolved. That is a deliberate trade-off. For a release-gating check like this, failing loudly is the point. We want the release process to tell us when the API can no longer provide the data that the application expects. The exact Gradle configuration will depend on the project and its variants, but the intended flow is: Production release ↓ Refresh snapshot ↓ Validate snapshot ↓ Build application This keeps normal development builds independent of the API while ensuring that production releases refresh the data that will actually ship to users. ### Let the Build Fail When the Snapshot Is Invalid This is one part I feel strongly about. If the snapshot cannot be refreshed or validated, the production build should fail. It might be tempting to keep the previous snapshot and allow the build to continue, but that can hide exactly the kind of problems this mechanism is supposed to help us detect. The refresh request could fail because: API version was deprecated Endpoint was renamed Endpoint was removed Authentication changed Server is unavailable Network request failed Response format changed Response is malformed If we silently keep yesterday’s snapshot, the build succeeds even though we no longer know whether that snapshot is valid for the current application. Instead, I would rather have: Production release ↓ Refresh snapshot ↓ Request successful? / \ No Yes ↓ ↓ Fail build Validate ↓ Response valid? / \ No Yes ↓ ↓ Fail build Write snapshot ↓ Build succeeds This gives us something valuable: a definitive build-time check. A successful production build tells us that the snapshot was actually retrieved and passed validation. We are not guessing: > “The old snapshot is probably still fine.” We are making a stronger statement: > “The fallback shipped with this release was successfully refreshed and validated.” That also means this Gradle task becomes more than a file-generation task. It becomes a small integration check between the application and the API. ### Validate Before Replacing the Snapshot The example above intentionally keeps the validation step generic. In a production implementation, I would not write whatever comes back from the endpoint directly into the resource. A successful HTTP request does not necessarily mean that the response is valid for the application. For example, the endpoint could return a 200 response containing an unexpected structure: { "unexpected": "structure" } If that response replaced our snapshot, we would simply move the failure from build time to runtime. Instead: Fetch ↓ Validate HTTP response ↓ Parse response ↓ Validate expected structure ↓ Write snapshot If any validation fails, the production build fails. The existing snapshot should also remain untouched until the new response has been successfully retrieved and validated. The goal is simple: > A successful build should produce a known-good snapshot. ### A Packaged Snapshot Is Different from a Local Cache At first, this might sound similar to keeping the previous API response in local storage. There is an important difference. A local cache only helps if the application has already received and stored the data. On a fresh installation: Install application ↓ First launch ↓ API request fails ↓ Local cache? ↓ Nothing available The same thing happens if the user clears the application’s storage. A packaged snapshot does not have that limitation: Install application ↓ First launch ↓ API request fails ↓ Packaged snapshot exists ↓ Use fallback The fallback is already part of the application. This makes it particularly useful for first-launch failures and other situations where there is no previously persisted state to fall back to. ### Choose Data That Can Safely Be Stale This approach is not intended for every API. The data should generally be common application data, such as configuration or relatively stable reference data. It should not be user-specific state such as: - account balances - individual orders - authentication state - user-specific permissions - transactional data Those values belong to the individual user or depend heavily on current server state. More generally, the key question is not: > How often does this API change? It is: > Can the application safely continue with a snapshot of this data? A configuration value might be a week old and still be perfectly usable. Another value might change only occasionally but still be unsafe to use when stale. So I would think about it this way: Can stale data still produce a valid application state? | / \ Yes No | | Snapshot Retry / block That is a much better criterion than simply classifying APIs as “frequently changing” or “infrequently changing.” ### Graceful Degradation Depends on the Data The reason an API request failed does not automatically determine whether the fallback is useful. For example, suppose the device has no internet connection: API request ↓ No network ↓ Use packaged snapshot That can be completely reasonable if the data is safe to use while stale. The same can be true when a server or service is temporarily unavailable. The real question is: > Can the user safely continue using the snapshot? Suppose a configuration API determines how a screen behaves. If the server is temporarily unavailable, the latest packaged configuration may allow the user to continue without being unnecessarily blocked. But if the API provides information that is required to safely perform a transaction, an old snapshot could create an invalid state. In that situation, the correct behavior is to retry or stop the flow. This is why graceful degradation should be designed around the purpose of the data, not merely the reason the request failed. The goal is not to make every failure invisible. The goal is to avoid blocking the user when the application can safely continue. ### The Snapshot Is External State Captured at Build Time There is one other property of this approach worth understanding. The packaged data is a snapshot of external state at build time. Suppose we build version 1.4.0 today: Version: 1.4.0 config_defaults.json ↓ Response A Later, the API changes and we build the same source again: Version: 1.4.0 config_defaults.json ↓ Response B The two artifacts can therefore contain different fallback data even if the source code is identical. But I don’t think that is inherently a problem. The application already depends on external API state at runtime. The response can change between two executions of the same application without the application itself changing. Here, we are simply capturing one of those responses during the build so that it can be used later when the live API is unavailable. The artifact is effectively saying: > This is the latest known valid data available when this application was built. That is precisely what we want from a fallback snapshot. For traceability, we could also record when the snapshot was generated: Application version: 1.4.0 Defaults snapshot: 2026-08-23T05:30:00Z That lets us identify the state that was packaged with a particular release. ### Where Build-Time Snapshots Fit into Graceful Degradation This approach does not replace local caching, synchronization, retries, or proper failure handling. It is another layer, and it solves something local caching cannot: a local cache only helps once the application has already received and stored data, so a fresh install or a cleared cache leaves nothing to fall back to. A packaged snapshot is already part of the application, so it is available even on first launch. A fallback strategy could look something like: Live API ↓ Local cache ↓ Packaged API snapshot ↓ Hard-coded default Each layer represents a different level of freshness. The live API is the current source of truth. The local cache holds previously received state. The packaged snapshot holds the latest known-valid common data from build time. The hard-coded default is the final, manually maintained fallback. Not every application needs every layer. The right combination depends on what the data represents and how safe it is to operate with stale information. ### The Bigger Idea: Moving Default Maintenance into the Build The Gradle task itself is not the interesting part. What I found interesting was changing who maintains the fallback. Instead of asking developers to manually keep this: default = X in sync with an evolving API, we can sometimes generate it from the API itself: default = latest known valid API response That gives us a fallback that evolves with the source of truth. It also solves a problem that local storage cannot solve on its own: the application can have meaningful fallback data even on its very first launch. But this approach should not become an excuse to use stale data everywhere. For every fallback, I think we should ask three questions: > What does this data represent? > How dangerous is it if the data is stale? > Can the user safely continue with it? If the answer supports degradation, a build-time snapshot can be a simple and effective way to make that part of the application more resilient. If it does not, the right solution is to retry, synchronize, or keep the user at the current state. Graceful degradation is not about avoiding every failure. It is about knowing which failures we can safely degrade from, and having a fallback that is actually valid for that situation. --- Build-Time Snapshots: A Better Way to Provide Defaults was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.// ❌ Dangerous: Swallowing CancellationException fun loadData() { viewModelScope.launch { try { val response = repository.fetchRemoteData() _uiState.value = UiState.Success(response) } catch (e: Exception) { // Catches CancellationException! The coroutine continues running _uiState.value = UiState.Error("Failed to load data") } } } ### The Fix Rethrow CancellationException explicitly, or catch domain-specific exceptions rather than general Exception. // ✅ Refactored: Preserving Cancellation fun loadData() { viewModelScope.launch { try { val response = repository.fetchRemoteData() _uiState.value = UiState.Success(response) } catch (e: Exception) { if (e is CancellationException) throw e _uiState.value = UiState.Error("Failed to load data") } } } // ✅ Idiomatic alternative: Filtering Exception types inline fun <T> Result<T>.onFailureExceptCancellation(action: (Throwable) -> Unit): Result<T> { exceptionOrNull()?.let { if (it !is CancellationException) action(it) } return this } ### 2. Using async Without supervisorScope for Parallel Execution When firing multiple concurrent requests with async, developers often assume an error in one request will be caught by a try-catch block wrapping await(). ### The Anti-Pattern Under standard structured concurrency (coroutineScope), if any child coroutine launched via async throws an exception, it immediately cancels its parent and all sibling coroutines—before await() is even reached. // ❌ Dangerous: One failure cancels the parent scope immediately suspend fun fetchDashboardData(): DashboardData = coroutineScope { // If fetchUser() fails, it immediately cancels the parent coroutineScope // and fetchNotifications(), throwing the exception out of coroutineScope val userDeferred = async { userRepository.getUser() } val notificationsDeferred = async { notificationRepository.getNotifications() } try { DashboardData( user = userDeferred.await(), notifications = notificationsDeferred.await() ) } catch (e: Exception) { // This catch block might never receive the original exception DashboardData.Empty } } ### The Fix Wrap parallel async operations in a supervisorScope. In a supervisorScope, a failure in one child job does not automatically propagate cancellation to siblings or parent jobs. // ✅ Refactored: Isolated failure with supervisorScope suspend fun fetchDashboardData(): DashboardData = supervisorScope { val userDeferred = async { userRepository.getUser() } val notificationsDeferred = async { notificationRepository.getNotifications() } val user = runCatching { userDeferred.await() }.getOrNull() val notifications = runCatching { notificationsDeferred.await() }.getOrDefault(emptyList()) DashboardData( user = user ?: User.Guest, notifications = notifications ) } ### 3. High-Frequency Context Switching in Hot Loops or Flows withContext(Dispatchers.IO) is essential for offloading blocking I/O work from the main thread. However, switching execution contexts incurs non-trivial allocation and dispatch overhead. ### The Anti-Pattern Invoking withContext inside a loop processing hundreds or thousands of items causes excessive context switches, thread queuing, and garbage collector pressure. // ❌ Inefficient: Context switching on every iteration class UserRepository(private val database: AppDatabase) { suspend fun processUserRecords(userIds: List<String>): List<UserProfile> { return userIds.map { id -> // Switching dispatchers 1000 times inside the loop! withContext(Dispatchers.IO) { database.userDao().getUserById(id) } } } } ### The Fix Move withContext outside the loop so that the entire batch runs inside a single dispatcher context shift. // ✅ Optimized: Single context shift for the entire batch class UserRepository(private val database: AppDatabase) { suspend fun processUserRecords(userIds: List<String>): List<UserProfile> = withContext(Dispatchers.IO) { userIds.map { id -> database.userDao().getUserById(id) } } } ### 4. Unconfined Global Scope Leaks in Long-Lived Singletons Singletons or application-scoped components often need to launch background jobs (e.g., synchronizing local database with backend, logging analytics). ### The Anti-Pattern Using GlobalScope or CoroutineScope(Dispatchers.IO) directly without a controlled lifecycle creates unmanaged jobs. If an operation hangs, gets stuck in an infinite loop, or throws an unhandled exception, it cannot be safely cancelled from outside. // ❌ Anti-Pattern: Unbounded GlobalScope usage object AnalyticsTracker { fun trackEvent(event: String) { // GlobalScope lives for the entire process duration and lacks a Job hierarchy GlobalScope.launch(Dispatchers.IO) { api.sendAnalytics(event) } } } ### The Fix Inject a dedicated CoroutineScope tied to the Application lifecycle, backed by SupervisorJob(). // ✅ Refactored: Injectable Application Scope class ApplicationScope @Inject constructor() : CoroutineScope { override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.Default } @Singleton class AnalyticsTracker @Inject constructor( private val appScope: ApplicationScope, private val api: AnalyticsApi ) { fun trackEvent(event: String) { appScope.launch { try { api.sendAnalytics(event) } catch (e: Exception) { if (e is CancellationException) throw e Log.e("Analytics", "Failed to send event", e) } } } } ### 5. Exposing Mutable Reactive Streams from Repositories MutableStateFlow and MutableSharedFlow allow internal state manipulation. Exposing them directly from Repositories or ViewModels breaks encapsulation and allows external callers to mutate internal state directly. ### The Anti-Pattern Exposing MutableStateFlow in public interfaces. // ❌ Anti-Pattern: External classes can modify repository state directly class UserSessionRepository { val userStatus = MutableStateFlow<UserStatus>(UserStatus.LoggedOut) } // In some distant ViewModel: repository.userStatus.value = UserStatus.LoggedIn // Bypass validation! ### The Fix Expose StateFlow or SharedFlow as read-only properties using .asStateFlow() or .asSharedFlow(). // ✅ Refactored: Enforcing Unidirectional Data Flow class UserSessionRepository { private val _userStatus = MutableStateFlow<UserStatus>(UserStatus.LoggedOut) val userStatus: StateFlow<UserStatus> = _userStatus.asStateFlow() fun loginUser(credentials: Credentials) { // Controlled internal mutation _userStatus.value = UserStatus.LoggedIn } } ### Code Review Checklist for Coroutines in Production When reviewing Kotlin coroutine code before merging, check against these rules: Hope this article is a good read. Thanks for reading this article. Let’s connect on LinkedIn: https://www.linkedin.com/in/dilip-chandar-97570158 --- Kotlin Coroutines Anti-Patterns in Production: 5 Subtle Traps That Leak Memory and Break… was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.