class CityViewModel : ViewModel() {
private val _cityData = MutableLiveData<City>()
private val _cities = CityDataProvider().getCities()
private var _currentIndex = 0
private val _delay = 2000L
init {
loop()
}
private fun loop(){
Handler(Looper.getMainLooper()).postDelayed({updateCity()
},_delay)
}
private fun updateCity(){
_currentIndex++
_currentIndex %= _cities.size
_cityData.value = _cities[_currentIndex]
loop()
}
/**
* Returns a LiveData object containing City data.
*
* Note: This function returns LiveData instead of MutableLiveData to promote encapsulation
* and abstraction, adhering to the ViewModel guidelines. Exposing MutableLiveData directly
* would grant external components mutable access to the ViewModel's internal state, which
* can lead to unintended modifications and violate the principles of encapsulation.
* By returning LiveData, external components can only observe changes to the data,
* maintaining a clear separation of concerns and ensuring data consistency.
*/
fun getCityData() : LiveData<City> = _cityData
}
@Composable
fun CityDetails(city: City) {
Card(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
elevation = CardDefaults.cardElevation(8.dp),
shape = RoundedCornerShape(16.dp)
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Image(
painter = painterResource(id = city.img),
contentDescription = null,
)
Text(
text = city.name,
fontSize = 20.sp,
textAlign = TextAlign.Center,
modifier = Modifier.padding(vertical = 8.dp)
)
Text(
text = "Population: ${city.population}",
fontSize = 16.sp,
textAlign = TextAlign.Center
)
}
}
}
class MainActivity : ComponentActivity() {
private val cityViewModel : CityViewModel by viewModels<CityViewModel> ()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CityMVVMTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
//HOW TO IMPLEMENT THIS VIEWMODEL??
}
}
}
}
}
hi, im trying to learn this viewmodel concept. ive create the viewmodel class and a composable that suppose to show me the city, image, and population.
im not sure how to implement it in MainActivity
any help would be great