Home > OS >  How to use Viewmodel with Jetpack compose
How to use Viewmodel with Jetpack compose

Time:10-28

I am trying to use ViewModel with Jetpack Compose,

By doing a number increment.

But it's not working. Maybe I'm not using the view model in right way.

Heres my Main Activity code

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Greeting()
        }
    }
}

@Composable
fun Greeting(
    helloViewModel: ViewModel = viewModel()
) {
    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.fillMaxSize()
    ) {
        Text(
            text = helloViewModel.number.toString(),
            fontSize = 60.sp,
            fontWeight = FontWeight.Bold
        )
        Button(onClick = { helloViewModel.addNumber() }) {
            Text(text = "Increment Number ${helloViewModel.number}")
        }

    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    JetpackcomposepracticeTheme {
        Greeting()
    }
}

And here is my Viewmodel class.

It works fine with xml.

How do i create the object of view model:

class ViewModel: ViewModel() {
    var number : Int = 0
    fun addNumber(){
        number  
    }
}

CodePudding user response:

Compose can recompose when some with mutable state value container changes. You can create it manually with mutableStateOf(), mutableStateListOf(), etc, or by wrapping Flow/LiveData.

class ViewModel: ViewModel() {
    var number : Int by mutableStateOf(0)
    fun addNumber(){
        number  
    }
}

I suggest you start with state in compose documentation, including this youtube video which explains the basic principles.

  • Related