為什麼是MVI而不是MVVM
MVVM作為流行的架構模式,應用在 Compose上,并沒有大的問題或者設計缺陷。但是在使用期間,發現了并不适合我的地方,或者說是使用起來不順手的地方:
- 資料觀察者過多:如果界面有多個狀态,就要多個 LiveData 或者 Flow,維護麻煩。
- 更新 UI 狀态的來源過多:資料觀察者多,并行或同時更新 UI,造成不必要的重繪。
- 大量訂閱觀察者函數,也沒有限制:存儲和更新沒有分離,容易混亂,代碼臃腫。
單向資料流
單向資料流 (UDF) 是一種設計模式,在該模式下狀态向下流動,事件向上流動。通過采用單向資料流,您可以将在界面中顯示狀态的可組合項與應用中存儲和更改狀态的部分分離開來。
使用單向資料流的應用的界面更新循環如下所示:
- 事件:界面的某一部分生成一個事件,并将其向上傳遞,例如将按鈕點選傳遞給 ViewModel 進行處理;或者從應用的其他層傳遞事件,如訓示使用者會話已過期。
- 更新狀态:事件處理腳本可能會更改狀态。
- 顯示狀态:狀态容器向下傳遞狀态,界面顯示此狀态。
以上是官方對單向資料流的介紹。下面介紹适合單項資料流的架構 MVI。
MVI
MVI 包含三部分,Model — View — Intent
- Model 表示 UI 的狀态,例如加載和資料。
- View 根據狀态展示對應 UI。
- Intent 代表使用者與 UI 互動時的意圖。例如點選一個按鈕送出資料。
可以看出 MVI 完美的符合官方推薦架構 ,我們引用 React Redux 的概念分而治之:
- State 需要展示的狀态,對應 UI 需要的資料。
- Event 來自使用者和系統的是事件,也可以說是指令。
- Effect 單次狀态,即不是持久狀态,類似于 EventBus ,例如加載錯誤提示出錯、或者跳轉到登入頁,它們隻執行一次,通常在 Compose 的副作用中使用。
實作
首先我們需要限制類型的接口:
interface UiState
interface UiEvent
interface UiEffect
然後建立抽象的 ViewModel :
abstract class BaseViewModel< S : UiState, E : UiEvent,F : UiEffect> : ViewModel() {}
對于狀态的處理,我們使用
StateFlow
,
StateFlow
類似
LiveData
但具有初始值,是以需要一個初始狀态,這也和 UI 需要初始狀态呼應。這裡為什麼不使用更簡單直白的
MutableState
?,主要是因為考慮到
Flow
的操作符十分強大。
private val initialState: S by lazy { initialState() }
protected abstract fun initialState(): S
private val _uiState: MutableStateFlow<S> by lazy { MutableStateFlow(initialState) }
val uiState: StateFlow<S> by lazy { _uiState }
對于意圖,即事件,要能接收和處理,接收意圖也即意味着要處理邏輯:
private val _uiEvent: MutableSharedFlow<E> = MutableSharedFlow()
init {
subscribeEvents()
}
/**
* 收集事件
*/
private fun subscribeEvents() {
viewModelScope.launch {
_uiEvent.collect {
// reduce event
}
}
}
fun sendEvent(event: E) {
viewModelScope.launch {
_uiEvent.emit(event)
}
}
然後 Reducer 處理事件,更新狀态,一開始是在
handleEvent
裡處理,後來發現一般的邏輯都是挂起函數,比如請求和送出資料,而執行完需要更新狀态,是以就把這個函數定義為
suspend
,并且傳回狀态的話,主動更新狀态,這樣
handleEvent
函數更簡潔:
/**
* 處理事件,更新狀态
* @param state S
* @param event E
*/
private fun reduceEvent(state: S, event: E) {
viewModelScope.launch {
handleEvent(event, state)?.let { newState -> sendState { newState } }
}
}
protected abstract suspend fun handleEvent(event: E, state: S): S?
單一的副作用:
private val _uiEffect: MutableSharedFlow<F> = MutableSharedFlow()
val uiEffect: Flow<F> = _uiEffect
protected fun sendEffect(effect: F) {
viewModelScope.launch { _uiEffect.emit(effect) }
}
三駕馬車已經封裝完畢,下面利用這個架構實作一個簡易的 Todo 應用。
使用
接下來實作一個 Todo 應用,打開應用擷取曆史任務,點選加号增加一條新的任務,完成任務後後
Toast
提示。
首先分析都有哪些狀态:
- 是否在加載曆史任務
- 是否添加新任務
- 任務清單
建立狀态:
internal data class TodoState(
val isShowAddDialog: Boolean=false,
val isLoading: Boolean = false,
val todoList: List<Todo> = listOf(),
) : UiState
然後分析有哪些意圖:
- 加載任務(自動加載,是以省略)
- 顯示任務
- 加載框的顯示隐藏
- 添加新任務
- 完成任務
internal sealed interface TodoEvent : UiEvent {
data class ShowData(val items: List<Todo>) : TodoEvent
data class OnChangeDialogState(val show: Boolean) : TodoEvent
data class AddNewItem(val text: String) : TodoEvent
data class OnItemCheckedChanged(val index: Int, val isChecked: Boolean) : TodoEvent
}
而單一事件就一種,完成任務時候的提示:
internal sealed interface TodoEffect : UiEffect {
// 已完成
data class Completed(val text: String) : TodoEffect
}
界面
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun TodoScreen(
viewModel: TodoViewModel = viewModel(),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
viewModel.collectSideEffect { effect ->
Log.e("", "TodoScreen: collectSideEffect")
when (effect) {
is TodoEffect.Completed -> Toast.makeText(context,
"${effect.text}已完成",
Toast.LENGTH_SHORT)
.show()
}
}
// LaunchedEffect(Unit) {
// viewModel.uiEffect.collect { effect ->
// Log.e("", "TodoScreen: LaunchedEffect")
//
// when (effect) {
// is TodoEffect.Completed -> Toast.makeText(context,
// "${effect.text}已完成",
// Toast.LENGTH_SHORT)
// .show()
// }
// }
// }
when {
state.isLoading -> ContentWithProgress()
state.todoList.isNotEmpty() -> TodoListContent(
state.todoList,
state.isShowAddDialog,
onItemCheckedChanged = { index, isChecked ->
viewModel.sendEvent(TodoEvent.OnItemCheckedChanged(index, isChecked))
},
onAddButtonClick = { viewModel.sendEvent(TodoEvent.OnChangeDialogState(true)) },
onDialogDismissClick = { viewModel.sendEvent(TodoEvent.OnChangeDialogState(false)) },
onDialogOkClick = { text -> viewModel.sendEvent(TodoEvent.AddNewItem(text)) },
)
}
}
@Composable
private fun TodoListContent(
todos: List<Todo>,
isShowAddDialog: Boolean,
onItemCheckedChanged: (Int, Boolean) -> Unit,
onAddButtonClick: () -> Unit,
onDialogDismissClick: () -> Unit,
onDialogOkClick: (String) -> Unit,
) {
Box {
LazyColumn(content = {
itemsIndexed(todos) { index, item ->
TodoListItem(item = item, onItemCheckedChanged, index)
if (index == todos.size - 1)
AddButton(onAddButtonClick)
}
})
if (isShowAddDialog) {
AddNewItemDialog(onDialogDismissClick, onDialogOkClick)
}
}
}
@Composable
private fun AddButton(
onAddButtonClick: () -> Unit,
) {
Box(modifier = Modifier.fillMaxWidth()) {
Icon(imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier
.size(40.dp)
.align(Alignment.Center)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = onAddButtonClick
))
}
}
@Composable
private fun AddNewItemDialog(
onDialogDismissClick: () -> Unit,
onDialogOkClick: (String) -> Unit,
) {
var text by remember { mutableStateOf("") }
AlertDialog(onDismissRequest = { },
text = {
TextField(
value = text,
onValueChange = { newText ->
text = newText
},
colors = TextFieldDefaults.textFieldColors(
focusedIndicatorColor = Color.Blue,
disabledIndicatorColor = Color.Blue,
unfocusedIndicatorColor = Color.Blue,
backgroundColor = Color.LightGray,
)
)
},
confirmButton = {
Button(
onClick = { onDialogOkClick(text) },
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
) {
Text(text = "Ok", style = TextStyle(color = Color.White, fontSize = 12.sp))
}
}, dismissButton = {
Button(
onClick = onDialogDismissClick,
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
) {
Text(text = "Cancel", style = TextStyle(color = Color.White, fontSize = 12.sp))
}
}
)
}
@Composable
private fun TodoListItem(
item: Todo,
onItemCheckedChanged: (Int, Boolean) -> Unit,
index: Int,
) {
Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
colors = CheckboxDefaults.colors(Color.Blue),
checked = item.isChecked,
onCheckedChange = {
onItemCheckedChanged(index, !item.isChecked)
}
)
Text(
text = item.text,
modifier = Modifier.padding(start = 16.dp),
textDecoration = if (item.isChecked) TextDecoration.LineThrough else TextDecoration.None,
style = TextStyle(
color = Color.Black,
fontSize = 14.sp
)
)
}
}
@Composable
private fun ContentWithProgress() {
Surface(color = Color.LightGray) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
}
ViewModel
internal class TodoViewModel :
BaseViewModel<TodoState, TodoEvent, TodoEffect>() {
private val repository: TodoRepository = TodoRepository()
init {
getTodo()
}
private fun getTodo() {
viewModelScope.launch {
val todoList = repository.getTodoList()
sendEvent(TodoEvent.ShowData(todoList))
}
}
override fun initialState(): TodoState = TodoState(isLoading = true)
override suspend fun handleEvent(event: TodoEvent, state: TodoState): TodoState? {
return when (event) {
is TodoEvent.AddNewItem -> {
val newList = state.todoList.toMutableList()
newList.add(
index = state.goodstodoListList.size,
element = Todo(false, event.text),
)
state.copy(
todoList = newList,
isShowAddDialog = false
)
}
is TodoEvent.OnChangeDialogState -> state.copy(
isShowAddDialog = event.show
)
is TodoEvent.OnItemCheckedChanged -> {
val newList = state.todoList.toMutableList()
newList[event.index] = newList[event.index].copy(isChecked = event.isChecked)
if (event.isChecked) {
sendEffect(TodoEffect.Completed(newList[event.index].text))
}
state.copy(todoList = newList)
}
is TodoEvent.ShowData -> state.copy(isLoading = false, todoList = event.items)
}
}
}
優化
本來單次事件在
LaunchedEffect
裡加載,但是會出現在 UI 在停止狀态下依然收集新事件,并且每次寫
LaunchedEffect
比較麻煩,是以寫了一個擴充:
@Composable
fun <S : UiState, E : UiEvent, F : UiEffect> BaseViewModel<S, E, F>.collectSideEffect(
lifecycleState: Lifecycle.State = Lifecycle.State.STARTED,
sideEffect: (suspend (sideEffect: F) -> Unit),
) {
val sideEffectFlow = this.uiEffect
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(sideEffectFlow, lifecycleOwner) {
lifecycleOwner.lifecycle.repeatOnLifecycle(lifecycleState) {
sideEffectFlow.collect { sideEffect(it) }
}
}
}
其實還有許多Android 架構方面知識點,想跟大家分享,但由于文章篇幅長度限制,我已将其整理成了學習手冊的形式,供大家進行參考學習,有需要的可以 點選直接看↓↓↓方 進行參考學習
有需要的可以複制下方連結,傳送直達!!!
https://qr21.cn/CaZQLo?BIZ=ECOMMERCE
《Jetpack 全家桶知識筆記》
其實還有許多Android 架構方面知識點,想跟大家分享,但由于文章篇幅長度限制,我已将其整理成了學習手冊的形式,供大家進行參考學習,有需要的可以 直接點選此處↓↓↓ 進行參考學習