Android Architecture Components : ViewModel

ViewModel : UI-Related Data Object

One of the biggest challenges for an Android developer is keeping data across configuration changes such as screen rotation or during the recreation of Activity/Fragments after its been destroyed and recreated by the framework. Luckily the new Android Architecture Components library has ViewModel class that is intended to store and manage UI-related data so that the data survives configuration changes. 

Benefits

  • Keeps data across UI recreation
  • No need to repeat API calls and Database queries on UI recreation 
  • Keeps Activity/Fragments clean since work is now delegated to ViewModels
  • Share ViewModels between Fragments

Subclass ViewModel


To create a view-model just subclass ViewModel. View-models are responsible to provide data and keep reference to it. Our TimerViewModel lazily initializes TimerLiveData which is a LiveData implementation of a timer that counts seconds, read more about TimerLiveData and what exactly LiveData is used for in my post here.

Access And Observe


Now the Activity (or Fragments) can access this view-model via ViewModelProviders.of() function that takes Activity or Function that will become the owner of the view-model. Because our TimerLiveData is an observable, we can subscribe for value changes (that happen every second) and then update text view. To share a view-model between Fragments use getActivity() in ViewModelProviders.of() to get view-model owned by the parent Activity.

Results


Comments

  1. Appreciation for really being thoughtful and also for deciding on
    certain marvelous guides most people really want to be aware of.


    Android Training in Chennai


    Android Training in Bangalore

    ReplyDelete
  2. It’s always so sweet and also full of a lot of fun for me personally and my office colleagues to search your blog a minimum of thrice in a week to see the new guidance you have got.
    ME/M.Tech Project Center in Chennai | ME/M.Tech Project Center in Velachery

    ReplyDelete
  3. Thanks for this blog, keep sharing your thoughts like this...
    What is UI/UX
    Whay UI UX is Important

    ReplyDelete

Post a Comment

Popular posts from this blog

Android Architecture Components : LiveData

Building a Cryptocurrency with Kotlin : Part 1

Clean Code: Meaningful Names