Architecture Components based Android interview questions and answers


ViewModel


What is ViewModel?
Viewmodel is a Jetpack component, The class is designed to store and Manage the UI related data.
To handle data upon Lifecycle changes of activity/application, Like Screen orientation changes.

 

How to create ViewModel class in Android
To work with ViewModel we need to create a class that should be extends from ViewModel class.

 

How to instantiate ViewModel Class?
We can instantiate ViewModel class by two way

  • With default constructor(new key word in java)
  • With ViewModelProvider class

Class MyViewModel() extends ViewModel{
}
    1=> MyViewModel obj=new MyViewModel()
    1=> MyViewModel obj= ViewModelProvider(this).get(MyViewModel.class)


    
Note: Always use ViewModelProvider to create ViewModel objects rather than directly instantiating an instance of ViewModel.

 

Why we need to create ViewModel object with ViewModelProvider class?
Create ViewModel Object with ViewModelProvider    
1) It will return an existing viewmodel instance if already exists, other wise create new instance and return it.
2) It will create the ViewModel instance with the given Scope (Activity/Fragment)
3) The Instance is alive as long as the current scope is alive.

 

What is onCleared() method?
The onCleared method is a lifecycle method of viewmodel. This method will called when the Viewmodel is destroy.
So when we want to clear up any resources we need to do in this method.


What is Factory method pattern?
Factory method pattern is a creational design pattern which will uses factory methods to create objects.
A factory method which will return instance of the same class.

 

Why we will use FactoryMethod pattern while working with ViewModel object?
To pass arguments to ViewModel constructor is not a proper way and is not support to pass the arguments upon creating the instance.
To pass arguments to the ViewModel constructor we will use the Factory Method Pattern.

 

How to create ViewModelfactory pattern method?

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
   if (modelClass.isAssignableFrom(ScoreViewModel::class.java)) {
       return ScoreViewModel(finalScore) as T
   }
   throw IllegalArgumentException("Unknown ViewModel class")
}

 


Can we share the ViewModel between activities?

No, it’s not possible to share viewmodels between activities, whereas, we can share them among fragments.

What is the difference between ViewModel() and AndroidViewModel() ?

The AndroidViewModel class extends ViewModel class, so it has all the same functionality.

The only added functionality for AndroidViewModel is that it is context aware, when initialising AndroidViewModel we have to pass the application context as a parameter.

AndroidViewModel is helpful if we require context to get a system service or have a similar requirement(displaying a Toast message).

class MyAnViewModel (application: Application):

}

We can not construct a ViewModel instance on our own. We need to use the ViewModelProvider utility provided by Android to create instances of ViewModels.

3) When do we need to create a ViewModelFactory class?

aaa

LiveData

By using LiveData, we can Observe activity lifecycle method, so livedata will not trigger the change method if view is destroyed. There are many advantages of LiveData

  • Since livedata is present inside View Model it's retained on configuration change
  • Activity View is observing to live data
  • There is no memory leak as View Model doesn’t have any reference of activity
  • Observers have their own lifecycle so they are automatically cleaned when their Lifecycle is destroyed
  • When your activity goes into any state other than STARTED or RESUMED it will not call the onChanged method on the observer.
  • ViewModel exposes livedata that view observes it. Whenever livedata changes view gets notified and it could re-render itself.

What’s LiveData in Android Architecture Component and its Advantages?

LiveData component is an observable data holder class i.e, the contained value can be observed. LiveData is a lifecycle-aware component and thus it performs its functions according to the lifecycle state of other application components. Further, if the observer’s lifecycle state is active i.e., either STARTED or RESUMED, only then LiveData updates the app component. LiveData always checks the observer’s state before making any update to ensure that the observer must be active to receive it. If the observer’s lifecycle state is destroyed, LiveData is capable to remove it, and thus it avoids memory leaks. It makes the task of data synchronization easier.

LiveData

Advantages of LiveData component:

  • UI is updated as per the appropriate change in the data
  • It removes the stopped or destroyed activities which reduce the chance of app crash
  • No memory leaks as LiveData is a lifecycle-aware component.

To read more, refer to the article: Jetpack Architecture Components in Android


a

Workmanager

The recommended way going forward is using WorkManager APIs, that makes it easy to specify deferrable, asynchronous tasks and when they should run under the circumstances you choose, or recurring tasks that run at a specified interval. Internally WorkManager might use JobScheduler, Firebase-JobDispatcher, Executor, and AlarmManager for running the task

When you need to execute some background work fast and need a guarantee of that execution, create WorkerManager. Work manager APIs go beyond the only current state of the task and allows tasks to return data in key-value format. We are using LiveData to return data and state of Work. By using WorkManager, our activity can observe livedata and it will get notified whenever the task is finished.

For creating WorkManager, we need to create one subclass of the Worker class. This class has one abstract method called doWork(). As the name suggests, you need to perform the work you want to do in the background. This method will be called in the background/worker thread. Write a program to perform the task in this method.

In return, you have to return WorkerResult. Returning WorkerResult.SUCCESS indicates that the task you performed completed successfully. Returning WorkerResult.RETRY tells WorkManager to retry the work again. Returning WorkerResult.FAILURE indicates one or more errors occurred.

We can use  WorkManager for:

  • Uploading logs
  • Applying filters to images and saving the image
  • Periodically syncing local data with the network


aaaa

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Null safety based Kotlin interview questions and answers

What are Support Libraries ?