I have an application that has a statelist in the viewmodel. and i have function that adds a number in the list. when i click on a button, it adds the number in the list. but the changes is not getting reflected in another view.
MainActivity.kt
class MainActivity : ComponentActivity() {
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
Column {
Button(onClick = {viewModel.increaseCounter()}) {
Text("Increase counter")
}
CountView(viewModel.counter)
}
}
}
}
}
}
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun CountView(count: List<Int>) {
var coroutineScope = rememberCoroutineScope()
coroutineScope.launch {
Log.d("inside the coroutine ${count}")
}
}
MainViewModel.kt
class MainViewModel: ViewModel() {
var counter = mutableStateListOf<Int>()
fun increaseCounter() {
Log.d(">>>", "in viewmodel ${counter.size}")
counter.add(1)
}
}
Desired Result: Whenever i click on the button the log has to printed because it adds a number in the mutableStateList.
But when i change the mutableStateListOf into mutableStateOf and store some integer and change the integer the view gets recomposes and prints the log when i click on the button