'Fail with MVVM and Jetpack Compose

Trying to learn basics of MVVM with JetPack Compose. I made this simple code to learn how it works, but I´m struggling with the basics.

this is my code;

Composable;

@Composable
fun PantallaSencilla() {
    var viewModel = viewModel<MainViewModel>()
    var text by rememberSaveable { mutableStateOf(viewModel.returnName()) }
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        TextField(value = text, onValueChange = { text = it })

        Button(onClick = {
            viewModel.changeName("Mario")

        }) {
            Text(text = "Change name")
        }
    }
}

this is the ViewModel to control the states.

class MainViewModel : ViewModel() {
    var name : String by mutableStateOf("Pedro")

    fun returnName():String {
        return name
    }

    fun changeName(newName:String){
        name = newName
    }
}

Thanks for your comments.



Solution 1:[1]

Finally I arrived to this solution;

@Composable
fun PantallaSencilla() {
    var myViewModel = viewModel<MainViewModel>()

    myViewModel.name
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        TextField(value = myViewModel.name, onValueChange = {myViewModel.name = it })

        Button(onClick = {
            myViewModel.changeName("Mario")

        }) {
            Text(text = "Change name")
        }
        
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Juan_Lara