第 7 章:Navigation、ViewModel 整合與架構設計

約 6 分鐘

1. Screen 與 ViewModel 的標準分層模式

為了讓畫面既能接 ViewModel,又能輕鬆寫 @Preview 與 UI Test,實戰中最推薦的結構是 Route + Screen 雙層拆分:

  1. ProfileRoute(Stateful):負責取得 hiltViewModel()、用 collectAsStateWithLifecycle() 訂閱狀態、處理導航事件。
  2. ProfileScreen(Stateless):純粹接收 uiState: ProfileUiState 與 Lambda 事件(onEditClick: () -> Unit),完全不依賴 ViewModel!
@Composable
fun ProfileRoute(
    onNavigateToEdit: () -> Unit,
    viewModel: ProfileViewModel = hiltViewModel()
) {
    // ✅ 使用 collectAsStateWithLifecycle:App 進背景時自動停止收集,省電又安全
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    ProfileScreen(
        uiState = uiState,
        onEditClick = onNavigateToEdit,
        onRetry = viewModel::loadProfile
    )
}

@Composable
fun ProfileScreen(
    uiState: ProfileUiState,
    onEditClick: () -> Unit,
    onRetry: () -> Unit,
    modifier: Modifier = Modifier
) {
    // ✅ 這個函式完全不認識 ViewModel,可以輕鬆寫多個 @Preview 與自動化測試!
}

2. 一次性事件(One-off Events:導航 / Snackbar / Toast)怎麼處理?

這是 Android 架構爭論最多、也最容易寫出「旋轉螢幕重複跳頁」或「事件遺失」的地方。

  • Google 官方建議:盡可能把「需要顯示的提示(如 Error Message)」也當成 UiState 的一部分(顯示後由 UI 呼叫 viewModel.onErrorShown() 清除)。
  • 如果使用 Channel + receiveAsFlow() 傳送一次性事件,收集時務必搭配 repeatOnLifecycle(Lifecycle.State.STARTED) 與 Dispatchers.Main.immediate,避免事件在轉場瞬間遺失。

3. Slot API:打造高彈性的組合式元件

不要在共用元件裡塞滿十幾個布林旗標和字串參數(如 showLeadingIcon, titleText, subtitleText, badgeText…)。Compose 的強項是 Slot API(把 UI 區塊當成 @Composable () -> Unit 參數傳進去)!

❌ Bad:參數爆炸的僵化元件

@Composable
fun BadSettingRow(
    title: String,
    subtitle: String?,
    showSwitch: Boolean,
    switchChecked: Boolean,
    onSwitchChange: (Boolean) -> Unit,
    showArrow: Boolean
) { /* 內部充滿 if/else... */ }

✅ Good:用 Slot API 保留最大彈性

@Composable
fun GoodSettingRow(
    title: String,
    modifier: Modifier = Modifier,
    subtitle: String? = null,
    leadingContent: (@Composable () -> Unit)? = null,
    trailingContent: (@Composable () -> Unit)? = null
) {
    Row(
        modifier = modifier.fillMaxWidth().padding(16.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        leadingContent?.invoke()
        Column(modifier = Modifier.weight(1f)) {
            Text(title, style = MaterialTheme.typography.bodyLarge)
            if (subtitle != null) {
                Text(subtitle, style = MaterialTheme.typography.bodyMedium)
            }
        }
        trailingContent?.invoke()
    }
}

4. Type-Safe Navigation(Navigation Compose 2.8+)

新版 Navigation Compose 支援直接用 @Serializable data class/object 定義路由,徹底告別容易打錯字的字串拼接("detail/$userId"):

@Serializable object HomeRoute
@Serializable data class DetailRoute(val userId: String)

NavHost(navController = navController, startDestination = HomeRoute) {
    composable<HomeRoute> {
        HomeScreen(onUserClick = { id -> navController.navigate(DetailRoute(userId = id)) })
    }
    composable<DetailRoute> { backStackEntry ->
        val route: DetailRoute = backStackEntry.toRoute()
        DetailScreen(userId = route.userId)
    }
}

🔍 本章 Code Review 重點

  1. 畫面層是否誤用了 collectAsState() 而非 collectAsStateWithLifecycle()?
    • 在 Android 上一律使用 collectAsStateWithLifecycle()(需引入 lifecycle-runtime-compose)。
  2. 底層 UI 元件有沒有直接把 NavController 或 ViewModel 當參數傳進去?
    • 千萬不要把 NavController 傳進任何 Screen 或子元件! 應該只傳 Lambda(onNavigateBack: () -> Unit),這樣元件才不會與導航框架耦合。
  3. Screen 有沒有拆分成 Route(接 ViewModel)與 Stateless Screen(純 UI + @Preview)?
  4. 重複呼叫 navController.navigate() 會不會連點兩下打開兩個相同頁面?
    • 導航動作應確保冪等,或檢查 currentBackStackEntry?.lifecycle?.currentState == Lifecycle.State.RESUMED / 使用 launchSingleTop = true。