Wednesday, January 23, 2019

android kotlin - ViewModel LiveData example

MainActivity.kt

package com.cfsuman.jetpack

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import java.util.*


class MainActivity : AppCompatActivity() {

    private lateinit var mModel: RandomNumberViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the view model
        mModel = ViewModelProviders.of(this).get(RandomNumberViewModel::class.java)

        // Create the observer which updates the ui
        val randomNumberObserver = Observer<Int>{newNumber->
            // Update the ui with current data
            textView.text = "Current Number : $newNumber"
        }

        // Observe the live data, passing in this activity as the life cycle owner and the observer
        mModel.currentRandomNumber.observe(this,randomNumberObserver)

        // Button click listener
        button.setOnClickListener{
            // Change the data
            mModel.currentRandomNumber.value = Random().nextInt(50)
        }
    }
}
RandomNumberViewModel.kt

package com.cfsuman.jetpack

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class RandomNumberViewModel:ViewModel(){
    // Create a LiveData with a random number
    val currentRandomNumber:MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rootLayout"
        tools:context=".MainActivity"
        android:background="#fdfdfc">
    <Button
            android:text="Generate New Random Number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:layout_marginEnd="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginStart="8dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintHorizontal_bias="0.454"
            android:layout_marginTop="32dp" 
            app:layout_constraintTop_toTopOf="parent"/>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            android:text="Live Data"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:layout_marginTop="32dp"
            app:layout_constraintTop_toBottomOf="@+id/button" 
            android:layout_marginEnd="8dp"
            app:layout_constraintEnd_toEndOf="parent" 
            android:layout_marginStart="8dp"
            app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
gradle dependencies

def lifecycle_version = "2.0.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
More android examples