Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
How to use Viewmodel with Jetpack compose

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++
    }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)
        private set

    fun addNumber(){
        number++
    }
}

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!