简体   繁体   English

除了状态提升之外,我可以与 Jetpack Compose 一起使用的其他状态管理选项?

[英]Other state management options that I may use with Jetpack Compose, beyond State hoisting?

I am learning Jetpack compose, and I have been seen so far that lifting the state up to a composable's caller to make a composable stateless is the way to go.我正在学习 Jetpack compose,到目前为止,我已经看到将状态提升到可组合的调用者以使可组合的无状态是要走的路。 I`ve been using this pattern in my Compose apps.我一直在我的 Compose 应用程序中使用这种模式。

For an app state that I need to modify from many different places of the tree, I will have to pass around a lot of callbacks, This can become difficult to manage.对于我需要从树的许多不同位置修改的应用程序状态,我将不得不传递大量回调,这可能变得难以管理。

I have some previous experience with Flutter.我以前对 Flutter 有过一些经验。 The way Flutter deals with providing a state to its descendants in the tree to overcome the above, is to use other mechanisms to manage state, namely Provider + ChangeNotifier. Flutter 在树中为其后代提供状态以克服上述问题的方式是使用其他机制来管理状态,即 Provider + ChangeNotifier。

Basically, with Provider, a Provider Widget is placed in the tree and all the children of the provider will have access to the values exposed by it.基本上,使用 Provider,Provider Widget 被放置在树中,并且提供者的所有子级都可以访问它公开的值。

Are there any other mechanisms to manage state in Jetpack Compose apps, besides State hoisting?除了状态提升之外,还有其他机制来管理 Jetpack Compose 应用程序中的状态吗? And, what would you recommend?而且,你会推荐什么?

If you need to share some data between views you can use view models .如果您需要在视图之间共享一些数据,您可以使用视图模型

@Composable
fun TestScreen() {
    val viewModel = viewModel<SomeViewModel>()
    Column {
        Text("TestScreen text: ${viewModel.state}")
        OtherView()
    }
}

@Composable
fun OtherView() {
    val viewModel = viewModel<SomeViewModel>()
    Text("OtherScreen text: ${viewModel.state}")
}

class SomeViewModel: ViewModel() {
    var state by mutableStateOf(UUID.randomUUID().toString())
}

The hierarchy topmost viewModel call creates a view model - in my case inside TestScreen .层次结构最顶层的viewModel调用创建了一个视图模型——在我的例子中是在TestScreen中。 All children that call viewModel of the same class will get the same object.所有调用同一类的viewModel的孩子都将获得相同的对象。 The exception to this is different destinations of Compose Navigation, see how to handle this case in this answer .例外情况是 Compose Navigation 的不同目的地,请参阅如何在此答案中处理这种情况。

You can update a mutable state property of view model, and it will be reflected on all views using that model.您可以更新视图模型的可变状态属性,它将反映在使用该模型的所有视图上。 Check out more about state in Compose .在 Compose 中查看有关状态的更多信息。

The view model lifecycle is bound to the compose navigation route (if there is one) or to Activity / Fragment otherwise, depending on where setContent was called from.视图模型生命周期绑定到 compose 导航路由(如果有)或Activity / Fragment否则,取决于从哪里调用setContent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM