• Mobility
Linked In Facebook Twitter

How to use LiveData and ViewModel in your next development project?


What is LiveData?

LiveData is a data holder class that follows Observer pattern. It holds primitives and collection types and notifies its observers when the data has changed. The UI components of LiveData observes relevant data. Unlike a regular observable, LiveData is lifecycle-aware meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state

Feature upgradation in Specification Version 2

Apple added a small update in Core ML’s second version by providing support for 16-bit floating-point weights. It helps in making the mlmodel files about 2X smaller. Other significant features that were added include: weight quantization for smaller mlmodel files (without any change in the inference speed), flexible input sizes, API added batch predictions and better support for dealing with sequential data.

Advantage of LiveData

  • No need to handle the lifecycle manually: Live data is a lifecycle-aware component and it can automatically manage lifecycle. So, there is no need to manage the lifecycle manually.
  • Data receive during configuration change: When ViewModel is used, data will not be lost due to configuration changes. You can get the latest data after every activity or fragment recreated.
  • No memory leakage: Observers are associated with the lifecycle objects and detach themselves when their associated lifecycle is destroyed.
  • Update UI if any changes are reflected in LiveData: LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there's any change.
  • Lifecycle aware: If the observer's lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.

Steps to implement LiveData objects

  • Create an object of LiveData to hold a certain type of data. This is usually done within your ViewModel class.
  • Create an Observer instance that defines the onChanged () method, which controls what happens when the data held by LiveData object/s changes. You usually create an Observerobject in a UI controller, such as an activity or fragment. Associate the Observer object to the LiveData object using the observe () method. The observe () method takes a LifecycleOwner object. This subscribes Observer object to the LiveData object so that it is notified of changes. You usually attach the Observerobject in a UI controller, such as an activity or a fragment

How to create an instance of LiveData?

LiveData can hold any type of data, including objects that implement Collections, such as a List. A LiveData object is created within a ViewModel class and is accessed via a getter method, below is sample code to create an object of LiveData


    class DemoActivity: AppCompatActivity () {
      private lateinit var model: AddressViewModel
      override fun onCreate (savedInstanceState: Bundle?) {
          super. onCreate(savedInstanceState)
          // Get the ViewModel.
          model = ViewModelProviders.of(this).get(AddressViewModel::class.java)
          // Create the observer which updates the UI.
          val addressObserver = Observer {newAddress ->
              nameTextView.text = newAddress
          }
      // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
      model. currentAddress.observe(this, addressObserver)
      }
  }
  
    

How to update LiveData objects?

To update the LiveData object you have to use MutableLivedata class, because LiveData has no publicly available methods to update the stored data. The MutableLiveData class has the setValue(T) and postValue(T) methods publicly and you must use these if you need to edit the value stored in a LiveData object. Usually, MutableLiveData is used in the ViewModel and then the ViewModel only exposes immutable LiveData objects to the observers.


      val otherAddress= "Sector 22"
      model. currentAddress.setValue(otherAddress)

    
      

What is a ViewModel?

ViewModel provides LiveData to the user interface and acts as a mediator between the Repository and the UI components (such as activity and fragment). The ViewModel class is designed to store and manage all UI related data in a lifecycle conscious way. It allows the data to survive configuration changes such as screen rotations. Viewmodel objects are automatically retained during configuration changes so that the data they hold is immediately available to the next activity or fragment instance. For example:

      
      class DemoActivity: AppCompatActivity () {
        override fun onCreate (savedInstanceState: Bundle?) {
              //Create a ViewModel the first time the system calls an activity's onCreate() method.
              /* Re-created activities receive the same DemoViewModel instance created by the 
              first activity.*/
              val model = ViewModelProviders.of(this)[DemoViewModel: class.java]
              model. getCustomers().observe(this, Observer>{ customers ->
              // update UI
                })
            }
        }
        
          
  
      
        

The Lifecycle of ViewModel

ViewModel can survive during the configuration changes. It means that even after the activity is destroyed and recreated after device rotation, you’ll still have the same ViewModel with the same data. The ViewModel remains in memory until the lifecycle is scoped out permanently: in case of a finished activity, or when a fragment is detached.

Below diagram demonstrates various lifecycle states of an activity as it undergoes a rotation and is finished: