MviComposeExtensions

1、MviComposeExtensions

接上篇MVI架构实践:MVI架构实践

针对Compose场景进行扩展,方便在Compose里面使用MVI架构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Composable
fun <VM : BaseMviViewModel<S, I>, S : MviUiState, I : MviUiIntent> VM.collectAsState(): State<S> {
return uiStateFlow.collectAsState(initial = state)
}

@Composable
fun <VM : BaseMviViewModel<S, I>, S : MviUiState, I : MviUiIntent, A> VM.collectAsState(prop1: KProperty1<S, A>): State<A> {
val mappedFlow = remember(prop1) { uiStateFlow.map { prop1.get(state) }.distinctUntilChanged() }
return mappedFlow.collectAsState(initial = prop1.get(state))
}

@Composable
fun <VM : BaseMviViewModel<S, I>, S : MviUiState, I : MviUiIntent, A> VM.collectAsState(block: (state: S) -> A): State<A> {
val mappedFlow = remember(block) { uiStateFlow.map { block(state) }.distinctUntilChanged() }
return mappedFlow.collectAsState(initial = block(state))
}

2、使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//获取state
val closeParams by viewModel.collectAsState(PanelUiState::closeParams)
TipsReport(extraParams = closeParams) {
Image(painter = BitmapPainter(getLocalImageBitmap(R.drawable.qmt_satisfy_tips_close)),
contentDescription = null,
modifier = Modifier
.height(24.dp)
.width(24.dp)
.align(Alignment.TopEnd)
.onClickExtension(extraParams = closeParams) {
//发送Intent
viewModel.setIntent(PanelUiIntent.TryExitSplitMode)
})
}