由 AI 協肋生成,文筆可能會有不順暢的情況出現。
到底在說什麼?
MVI (Model-View-Intent) 是 Android 複雜頁面或多人協作專案的頂級解方。
- 核心精髓: UDF (單向數據流) 永遠只朝一個方向跑,確保狀態可預測。
- MVI = 狀態即真理: 整個畫面只依賴一個唯一的、不可變的 State 物件。
- 現代化對應:
- Intent:使用者在 Composable 上的所有動作。
- View Model:負責處理 Intent,並釋出新的 State。
- Composable:純粹的畫面渲染器 (Render),只讀 State。
MVI 的黃金循環
MVI 就像一個不斷運轉的單向輸送帶,所有資料都不能逆流。
簡短程式碼示例 (概念模型)
| 物件 | 從屬關係 |
|---|---|
| ScreenState | ViewModel |
| ScreenEvent | ViewModel |
| ScreenIntent | ViewModel |
| ContentState | View |
| ContentIntent | View |
| 元件 | 資料流向 | 關鍵實作 |
|---|---|---|
| ViewModel | 發出 ScreenState / ScreenEvent
|
StateFlow (持續狀態), SharedFlow (一次性事件) |
| Screen Controller | 向下傳遞 ContentState向上傳遞 ScreenIntent接收 ScreenEvent
|
LaunchedEffect(viewModel.event)viewModel.onIntent(ClickDetails) viewModel.state.collectAsStateWithLifecycle()
|
| View | 接收 ContentState發出 ContentIntent
|
Button(onClick = { ... send Intent }) |

Top comments (0)