blob: 87d924e866cf922028066644286e3623e822770e [file] [view]
# Migration: mapLatest to mapDirect in SystemUI
## Overview
This document describes the effort to migrate simple, synchronous `mapLatest` usages in SystemUI Kotlin Flow pipelines to a new, lighter-weight alternative called `mapDirect`.
This migration aims to reduce coroutine cancellation overhead, simplify pipeline execution, and prevent subtle race conditions caused by unnecessary cancellations.
## The Problem with `mapLatest`
In SystemUI, `mapLatest` is frequently used to transform state in Flow pipelines. While `mapLatest` is useful when the transformation is asynchronous (e.g., database access or network requests), it is often used for **simple, synchronous transformations** (e.g., mapping a data class to a UI model, or extracting a field).
Using `mapLatest` for synchronous operations introduces several drawbacks:
1. **Cancellation Overhead:** Every time a new value is emitted upstream, `mapLatest` cancels the active coroutine block of the previous emission. If emissions are rapid, this causes constant coroutine cancellation and rescheduling.
2. **Race Conditions:** If downstream side-effects rely on the pipeline completing, premature cancellation via `mapLatest` can leave the system in an inconsistent state.
3. **Jank:** The overhead of constant coroutine cancellation and context switching can contribute to main-thread jank in critical UI paths.
## The Solution: `mapDirect`
To address this, we introduced `mapDirect` in `com.android.systemui.util.kotlin.Flow.kt`:
```kotlin
/**
* Aids the transition from `mapLatest` to `map` when the lambda is a non-suspend method.
*/
public inline fun <T, R> Flow<T>.mapDirect(noinline transform: (value: T) -> R): Flow<R> {
return this.conflate().map(transform)
}
```
### Key Differences:
* **Conflated but Synchronous:** Like `mapLatest`, `mapDirect` uses `conflate()` to ensure that if the downstream collector is slow, older intermediate values are dropped.
* **No Cancellation:** Unlike `mapLatest`, `mapDirect` uses standard `map`, meaning the transformation runs synchronously and is **never cancelled** mid-execution. This eliminates coroutine switching and cancellation overhead.
## Safe Rollout with `mapDirectFlagGuarded`
To ensure a safe migration, we also introduced a flag-guarded helper:
```kotlin
/**
* Standard mapLatest but migrated to mapDirect when the flag is enabled.
* Aids the transition from `mapLatest` to `mapDirect` with a feature flag.
*/
@OptIn(ExperimentalCoroutinesApi::class)
public inline fun <T, R> Flow<T>.mapDirectFlagGuarded(
noinline transform: (value: T) -> R
): Flow<R> {
return if (Flags.mapDirectMigration()) {
this.mapDirect(transform)
} else {
this.mapLatest(transform)
}
}
```
This allows us to migrate pipelines in place and verify performance/correctness before fully flipping the switch.
## Target Migrations
We have targeted key high-frequency pipelines for this migration:
1. **`MobileConnectionsRepositoryImpl.kt`:** Migrating mobile state mapping pipelines.
2. **`ConfigurationInteractor.kt`:** Migrating global configuration and resource mapping pipelines.
3. **`DemoMobileConnectionsRepository.kt`:** Migrating demo-mode mobile state pipelines.
4. **`ClockInteractor.kt`:** Migrating clock-related flow pipelines.
5. **`ClockRepositorySwitcher.kt`:** Migrating active clock tracking pipeline.
6. **`DisplayTypeRepository.kt`:** Migrating display type mapping pipeline.
7. **`KeyguardRepository.kt`:** Migrating keyguard state pipelines.
8. **`ScreenAwareAmbientLightModeMonitorRepository.kt`:** Migrating ambient light mode pipelines.
## Guidelines for Developers
When writing Flow pipelines in SystemUI:
* **Use `map`:** If the transformation is synchronous and you **do not** need conflation (you want to process every single emission).
* **Use `mapDirect`:** If the transformation is synchronous but you **do** need conflation (you only care about the latest state).
* **Use `mapLatest`:** ONLY if the transformation block contains **suspend functions** (e.g., calling an async repository or delaying) and you explicitly want to cancel the operation if a newer value arrives.
## Future Plans: Linter for Automatic Detection
To scale this migration and prevent new inefficient usages from being introduced, we plan to implement a custom **Android Lint** rule.
### Detection Logic
The linter will analyze Kotlin files in `SystemUI` and perform the following checks:
1. **Identify `mapLatest` Calls:** Find all occurrences of `.mapLatest { ... }`.
2. **Analyze Lambda Body:**
* Inspect the AST of the lambda expression using UAST (Universal AST).
* Check if the lambda body contains any **suspend function calls** or asynchronous operations (e.g., `delay`, calling a `suspend fun`).
3. **Flag Synchronous Usages:**
* If **no suspend calls** are found inside the lambda, flag it as a potential violation.
4. **Determine Recommendation:**
* Recommend migrating to `.map { ... }` if the pipeline does not require conflation.
* Recommend migrating to `.mapDirect { ... }` (or `.mapDirectFlagGuarded` during the migration phase) if conflation is intended.
### Implementation Strategy
* **Platform:** A custom Android Lint rule integrated into the `SystemUI-lint` module.
* **Severity:** Start as a **Warning** to allow developers to clean up existing code, with IDE Quick-Fix support to automatically rewrite the call.
* **Enforcement:** Eventually upgrade to an **Error** in presubmit (checkpatch/TAP) to block new inefficient `mapLatest` calls from being merged.