0Pricing
Jetpack Compose Academy · Lezione

viewModel() in una Composable

Ottenga e circoscriva correttamente un ViewModel.

viewModel() in una Composable è una lezione Jetpack Compose Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Jetpack Compose Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Jetpack Compose Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Getting a ViewModel

Inside a Composable you don’t construct a ViewModel with new. Instead you call the viewModel() function to fetch the right instance.

val vm: CounterViewModel = viewModel()

Where It Comes From

The viewModel() helper looks up the nearest lifecycle owner and returns the ViewModel scoped to it, creating one only if none exists yet.

Same Instance on Recomposition

Recomposition runs your function many times, yet viewModel() returns the same instance each time, so your state never resets unexpectedly.

Reading State From It

Once you hold the ViewModel, read its observable state and your Composable redraws whenever that state changes. The UI follows the data. 🔗

val vm: CounterViewModel = viewModel()
Text("Count: " + vm.count)

Calling Its Functions

Send user actions to the ViewModel by calling its functions from event lambdas, keeping the decision-making logic out of your Composable.

Button(onClick = { vm.increment() }) {
    Text("Add")
}

The Import

The function comes from the lifecycle Compose artifact. Import androidx.lifecycle.viewmodel.compose.viewModel to use it.

import androidx.lifecycle.viewmodel.compose.viewModel

Scoping by Default

By default the ViewModel is scoped to the host Activity or navigation destination, so all Composables in that scope share one instance. 🎯

Constructor Arguments

Need to pass dependencies? Provide a factory so the framework knows how to build a ViewModel that has constructor parameters.

val vm: CartViewModel = viewModel(factory = CartFactory(repo))

Hoist, Don’t Pass Down

Call viewModel() high up, near the screen root, then pass plain state and callbacks down to keep child Composables reusable.

Preview-Friendly Design

Because viewModel() needs a real owner, design children to take simple parameters so they still render in an isolated @Preview.

A Quick Pattern

The common flow is simple: obtain the ViewModel, read its state, and forward events to its functions. Three steps, every screen. ✨

Quick Check

Check how you obtain a ViewModel from a Composable.

Recap

Call viewModel() to fetch a scoped ViewModel, read its state to drive the UI, and forward user events to its functions instead of constructing it yourself.

Domande Frequenti

La lezione «viewModel() in una Composable» è gratuita?

Sì — il testo completo di «viewModel() in una Composable» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Jetpack Compose Academy, passa a CoddyKit PRO. Il corso Jetpack Compose Academy include 4 lezioni in totale.

Cosa imparerò in «viewModel() in una Composable»?

Ottenga e circoscriva correttamente un ViewModel. Eserciti Jetpack Compose Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Jetpack Compose Academy?

Non è richiesta alcuna esperienza precedente. Jetpack Compose Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «viewModel() in una Composable»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Jetpack Compose Academy?

Sì. Ogni lezione Jetpack Compose Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Perché il ViewModel sopravvive alla rotazione
  2. viewModel() in una Composable
  3. Modellare una classe dati UiState
  4. collectAsStateWithLifecycle
← Torna a Jetpack Compose Academy