从一个车载导航项目盘点 Compose 基础知识点:这些都是面试官爱问的

0 阅读1分钟

车载场景是 Compose 的“地狱难度副本”:一个 Activity 常驻数周不销毁、系统配置随时变、地图引擎是重如泰山的第三方 View、还要兼顾右舵车型和日夜模式。这个项目几乎把 Compose 的基础知识点全踩了一遍,盘点如下。

1. setContent 与 ViewCompositionStrategy —— Compose/View 混居的第一课

车机项目无法 100% Compose 化,地图、投屏都是传统 View。项目里 Activity 的根布局是 ViewBinding,只有内容区用 Compose:

binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.mapContent.setViewCompositionStrategy( ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed ) binding.mapContent.setContent { NaviTheme(...) { ComposeMap(mapView); MainContent(...) } }

知识点 :默认策略 DisposeOnDetachedFromWindow 在频繁 detach/attach 的场景(本项目窗口 resize 极频繁)会导致 Compose 树反复销毁重建。 DisposeOnViewTreeLifecycleDestroyed 改为跟随 ViewTreeLifecycle,配合 Activity configChanges 全接管,进程常驻数天 UI 树也不重建。

2. AndroidView 互操作 —— 把地图“镶”进 Compose

@Composable fun ComposeMap(mapView: MapView) { AndroidView( modifier = Modifier .fillMaxSize() .focusProperties { canFocus = false } .run { if (NaviTheme.isBlurRequired) hazeSource(state = mapHaze!!) else this }, factory = { mapView.apply { isFocusable = false descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS } }, update = { }, ) }

三个细节都是实战踩出来的: 

 - factory 里复用外部实例 而不是新建——地图初始化成本极高,Activity 重组时绝不能重复创建; 

- 焦点全禁 ——车机是物理旋钮/按键导航焦点体系,Compose 与 View 焦点树混住会抢焦,必须 FOCUS_BLOCK_DESCENDANTS ; 

- Modifier 链上挂毛玻璃。

3. MVI:ViewState / ViewIntent / ViewEvent 三件套

// Intent: 用户意图,单向流入 mapDialogsViewModel.sendIntent(MapDialogsIntent.ShowMapboxAttributionDialog) // ViewModel 内部: 

override fun handleIntent(intent: MapDialogsIntent) { when (intent) { is ShowMapboxAttributionDialog -> updateMapboxAttributionDialogState(true) is CloseMapboxTelemetryDialog -> updateTelemetryDialogState(false) ... } } 

 // State: 单一数据类,UI 只读 data class MapDialogsState(val isSplashShowing: Boolean, val isSetupDone: Boolean, ...)

4. 生命周期感知的状态收集 —— 别再用 collectAsState 了

车机 Activity 后台存活数小时是常态,订阅不感知生命周期就是内存泄漏 + 后台白耗 CPU。

// Compose 内收集 State val launcherUIState = mainViewModel.launcherUIState.collectAsStateWithLifecycle().value 

 // Flow 订阅加生命周期门 runtimePermissionChangeMonitor.permissionStateChanges .flowWithLifecycle(lifecycle, Lifecycle.State.RESUMED) .onEach { startupController.transition(StartupControllerEvent.PermissionStateChanged) } .launchIn(lifecycleScope)

collectAsStateWithLifecycle 在 STOPPED 时自动停止收集; flowWithLifecycle(RESUMED) 则利用了“回到前台必走 onResume 会重订阅一次”的特性做权限重查——注释里写得很清楚: “RESUMED: re-subscribing on every onResume emits once, re-checking permissions on each return to the app” 。

5.remember 的正确打开方式 —— remember 的是“计算”而非“值”

分屏 resize 是车机高频事件,项目把昂贵的窗口几何读取做了 key 化缓存( MainActivity.kt#L602-L611 ):

@Composable private fun realTimeWindowSize(launcherStatus: LauncherSplitScreenStateStatus): WindowSize { val configuration = LocalConfiguration.current val geometry = remember(configuration.screenWidthDp) { readWindowGeometry() } return launcherStatus.toRealTimeWindowSize( windowWidthPx = geometry.windowWidthPx, displayWidthPx = geometry.displayWidthPx, position = geometry.position, ) ?: launcherStatus.toWindowSize() }

知识点 : remember(key) { ... } 只在 key 变化时重算。这里 key 选 screenWidthDp 而不是整个 configuration ——因为 fontScale/locale 变化也会让 configuration 不等,但窗口几何没变,不该重算。另外注意 LocalConfiguration.current 本身就是响应式的:窗口 resize 时 Compose 自动触发重组,这是“配置驱动 UI”的典型案例。

6.重组控制:distinctUntilChanged 在 UI 边界的价值

状态机上游的 Flow 高频发射,UI 收集前先去重:

val state: Flow = _state.distinctUntilChanged() // 收集侧 combine(startupController.isReadyForMapInit, lifecycle.currentStateFlow) { ... } .distinctUntilChanged() .filter { shouldInitMap -> shouldInitMap }

知识点 :data class 的 equals 让 distinctUntilChanged 免费实现“值变了才重组”。地位昂贵的操作(这里是地图引擎 init)一定要放在去重之后——否则每次重组都可能重复触发。