0% found this document useful (0 votes)
116 views

Jetpack Compose - ViewModels

The document discusses how ViewModels can be used with Jetpack Compose to maintain state in a unidirectional data flow. It explains how LiveData is converted to State to allow values to automatically recompose the UI. An example is provided that shows a ViewModel with a LiveData counter, observing it as State in a Composable function, and updating the count through a button click.

Uploaded by

Jose Perez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

Jetpack Compose - ViewModels

The document discusses how ViewModels can be used with Jetpack Compose to maintain state in a unidirectional data flow. It explains how LiveData is converted to State to allow values to automatically recompose the UI. An example is provided that shows a ViewModel with a LiveData counter, observing it as State in a Composable function, and updating the count through a button click.

Uploaded by

Jose Perez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

2/11/21 10:30 Jetpack Compose: ViewModels

Hace 23 dias

Etiquetas
Androide
Reseña del libro
Negocio
Dardo
Django
Aleteo
Infra
Jetpack Compose
Kotlin
Programación

Alternar el modo oscuro

Jetpack Compose: ViewModels


Androide

21 de noviembre de 2020

If you have developed Android apps recently, chances are you are familiar with Jetpack's ViewModel and the unidirectional data flow.

Quick recap, in case you are not familiar with the unidirectional data flow term. You keep the permanent state of the screen in your ViewModel (that is retained with
configuration changes, e.g. screen rotations) and you expose that state with LiveData that your view "observes" and reacts to. When you want to make a change to your
screen, you notify the view model that does its business logic and emits a new value to the observing view. Long story short, data are moving only to a single direction
each time, thus unidirectional.

But how does this paradigm fits into this new UI world™? In the old world, the imperative UI world, when observing a LiveData you would explicitly instruct the view to
change the necessary value (e.g. myAwesomeLabel.text = newValue). How do you accomplish this since you cannot instruct directly the UI to change?

Meet State
It turns out it's even easier than before. In the declarative world, when you assign a value to a UI element, the UI gets redrawn automatically when that value changes.

Jetpack Compose's State<T> is responsible for this automatic "redraw" (in Compose it's called "recomposition"). So all you need to do is convert your LiveData to a State.
Unsurprisingly, this is easy to do.

Example
Un simple ejemplo es mucho mejor que un montón de palabras. Antes de comenzar, a excepción de las dependencias obvias para ViewModelJetpack Compose, necesitará
otro para convertir LiveDataa State:
dependencies {

[...]

implementation "androidx.compose.runtime:runtime-livedata:1.0.0-alpha07"

Como siempre, busque la última versión antes de copiar y pegar.

ViewModel
class MainViewModel : ViewModel() {

val counterLiveDate: LiveData<Int>

get() = counter

https://www.rockandnull.com/jetpack-compose-viewmodel/ 7/21
2/11/21 10:30 Jetpack Compose: ViewModels

private val counter = MutableLiveData<Int>()

private var count = 0

fun increaseCounter() {

counter.value = ++count

Un simple ViewModelque contiene algún estado, en este caso, un simple Intllamado countque se expone a la vista mediante un LiveData<Int>.

Vista

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContent {

// 1.

ScreenDemo()

@Composable

fun ScreenDemo(model: MainViewModel = viewModel()) { // 2.

val count by model.counterLiveData.observeAsState(0) // 3.

Demo("This is $count") { model.increaseCounter() }

// 4.

@Composable

fun Demo(text: String, onClick: () -> Unit = {}) {

Column {

BasicText(text)

Button(

onClick = onClick,

) {

BasicText(text = "Add 1")

// 5.

@Preview

@Composable

fun PreviewDemo() {

Demo("Preview")

1. Es posible que se pregunte dónde está, ViewModelya que no estamos obteniendo una instancia en Activity. Parece haber una forma más fácil en Redactar (ver a
continuación).
2. Este viewModel()valor predeterminado devolverá uno existente ViewModelo creará uno nuevo en el ámbito que se llama (en este caso del Activity). No es necesario
mantener una instancia separada de ViewModelen el Activity.
3. Aquí es donde convierte el LiveData<Int>en un Intque puede usar directamente en elementos de composición. Detrás de escena, hay un Compose State<Int>que se
encarga de "recomponer" la vista cada vez que hay un valor nuevo. El 0es el estado inicial.
4. Este Composable "sin estado" sólo sabe cómo dibujar algo que se le da (primer parámetro, text) y nos notifica cuando hay una interacción del usuario (segundo
parámetro, onClick).
5. Dividir Composables en "stateless" ( Demo) y "stateful" ( ScreenDemo), nos permite obtener una vista previa de Composable sin estado fácilmente sin tener que
reconstruir la aplicación cada vez mediante la anotación @Previewy el paso de algunos valores de muestra.

Con suerte, has comprendido cómo ViewModelse puede utilizar Jetpack en Jetpack Compose. Para obtener más información, consulte el excelente documento y laboratorio
de códigos . ¡Feliz codificación!

Vea más en esta serie exploratoria Jetpack Compose:

https://www.rockandnull.com/jetpack-compose-viewmodel/ 8/21

You might also like