class WeatherViewModel : ViewModel() {
var data = MutableStateFlow<Result<Model>>(Model())
private set
fun fetchData() {
viewModelScope.launch {
// Make API Call and update data
}
} }
@Composable fun MyApp() {
val visibleScreen by remember { mutableStateOf("weather") }
val weatherViewModel: WeatherViewModel = viewModel()
val data = weatherViewModel.data..asStateFlow().collectAsState()
if (visibleScreen == "weather") {
WeatherScreen(data) {
weatherViewModel.fetchData()
}
} else {
ForecastScreen(data) {
weatherViewModel.fetchData()
}
} }
@Composable fun WeatherScreen(weatherData: Result<Model>, refreshData: () -> Unit) {
}
@Composable fun ForecastScreen(weatherData: Result<Model>, refreshData: () -> Unit) {
}
1条答案
按热度按时间vngu2lb81#
因此,您可以在两个屏幕中使用相同的视图模型,这将是一个适合这种情况的解决方案。
编辑1:
请检查此代码。