简体   繁体   English

Android 组成 Navigation 和 ViewModel 无限网络调用

[英]Android compose Navigation and ViewModel infinite network calls

Currently I'm using compose with navigation and viewmodels.目前我正在使用带有导航和视图模型的组合。 The code of my NavHost is the following我的 NavHost 的代码如下

composable(MyRoute.name + "/{param}") { backStackEntry ->
                    val param = backStackEntry.arguments?.getString("id") ?: ""
                    val viewModel = hiltViewModel<MyViewModel>()
                    viewModel.setInitialParam(param)
                    viewModel.fetchDataFromNetwork()
                    MyComposable(
                        viewModel = viewModel
                    )
                }

The issue I'm facing is that viewModel.fetchDataFromNetwork() is called an infinite number of times (I guess it is recomposition) but how would I make the call once to fetch the data and then display it in the MyComposable我面临的问题是viewModel.fetchDataFromNetwork()被调用了无数次(我猜它是重组)但是我如何调用一次来获取数据然后在 MyComposable 中显示它

Use a LaunchedEffect to run your network call.使用LaunchedEffect运行您的网络调用。

See this for reference.请参阅此内容以供参考。

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

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