我报名参加金石计划1期应战——瓜分10万奖池,这是我的第3篇文章,点击检查活动详情
为什么是MVI而不是MVVM
MVVM作为盛行的架构形式,运用在 Compose上,并没有大的问题或许规划缺陷。可是在运用期间,发现了并不适合我的当地,或许说是运用起来不顺手的当地:
- 数据观察者过多:假如界面有多个状况,就要多个 LiveData 或许 Flow,保护费事。
- 更新 UI 状况的来历过多:数据观察者多,并行或同时更新 UI,形成不必要的重绘。
- 大量订阅观察者函数,也没有束缚:存储和更新没有别离,简略混乱,代码臃肿。
单向数据流
单向数据流 (UDF) 是一种规划形式,在该形式下状况向下活动,事情向上活动。经过采用单向数据流,您能够将在界面中显现状况的可组合项与运用中存储和更改状况的部分别离开来。
运用单向数据流的运用的界面更新循环如下所示:
以上是官方对单向数据流的介绍。下面介绍适合单项数据流的架构 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) }
}
}
}
国际惯例,上源码