viewModel() in einer Composable
Beziehen und begrenzen Sie ein ViewModel korrekt.
viewModel() in einer Composable ist eine kostenlose Jetpack Compose Academy-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Jetpack Compose Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Jetpack Compose Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.viewModelScoping 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.
Häufig gestellte Fragen
Ist die Lektion „viewModel() in einer Composable“ kostenlos?
Ja — der vollständige Text von „viewModel() in einer Composable“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Jetpack Compose Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Jetpack Compose Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „viewModel() in einer Composable“?
Beziehen und begrenzen Sie ein ViewModel korrekt. Du übst Jetpack Compose Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Jetpack Compose Academy zu starten?
Keine Vorkenntnisse erforderlich. Jetpack Compose Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „viewModel() in einer Composable“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Jetpack Compose Academy-Lektion Code schreiben und ausführen?
Ja. Jede Jetpack Compose Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Warum ein ViewModel Rotation übersteht
- viewModel() in einer Composable
- Eine UiState-Data-Class modellieren
- collectAsStateWithLifecycle