我有一个 ViewModel 类定义如下:
class MainActivityViewModel : ViewModel() {
private val _count = MutableStateFlow(0)
val count = _count.asStateFlow()
fun increaseCount() {
_count.update {
it + 1
}
}
}
我定义了一个 @Composable 函数,如下所示:
@Composable
fun MainActivityViewModel.MainScreen() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(text = "${count.collectAsState().value}")
Button(onClick = ::increaseCount) {
Text(text = "Increase")
}
}
}
然后我在 MainActivity 中使用 MainScreen 函数:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val viewModel = viewModel<MainActivityViewModel>()
viewModel.MainScreen()
}
}
}
}
}
我能想到两个优点:
我的问题是:
我运行上面的代码,看起来没问题。我是 koin 新手,还没有尝试过 koin。
我们应该将视图与 viewModel 分开的第一个原因,尤其是在 Compose 中,是 viewModel 的生命周期比屏幕长。它将通过重组而生存。然而,这样你就会将重组与你的 viewModel 纠缠在一起,这是非常错误的。