What are Kotlin MVVM and Livedata?

Adem Soner
Orion Innovation techClub
4 min readJan 6, 2023

Firstly, I am not an educator but, I would like to share information with you on the topics I have mentioned in the title, as I have learned and understood myself.

MVVM architecture is not only used in Kotlin, so we can say that it doesn’t come with Kotlin. However, on the Android part, Google tells us that it would be better to build the application using the Jetpack library. So let’s talk a little bit about how the MVVM architecture works.

As you can see in the image I put below, the Model, View, and View model is an MVVM structure. Well, what are these? Let me examine the picture and try to talk about it.

MVVM design pattern
MVVM Architecture Pattern

Model: We usually keep the records of the datasets that we will use in the application here. There is no connection to view in this layer. The necessary data is processed through the view model.

View: It creates the part that the user sees while using the application. Here, our UI elements and components are available for the user to use.

View Model: This layer is the part where we act as a bridge. Here, we use our model with the information from the user. I will talk about it a little bit, we communicate with the view using the LiveData we created in it.

The project structure can change according to the developer’s request. However, the most common and correct usage is as seen in the picture below. The MVVM structure we are talking about here is located in separate folders.

Project structure MVVM
Project Structure

Let me first talk about what LiveData is and then show it with codes.

LiveData: Observable is a data hold class. What makes LiveData special is that it can work with its lifecycle. What does it mean?

LiveData contains information about the state of the activity or the fragment it is in. The most important advantages of LiveData in my opinion are the advantages I mentioned below. You can find more detailed information by clicking the link.

LiveData advantages:

1→ Since it works with its life cycle, it self-destructs in case of extinction and does not take up memory space.

2→ It is produced from the Observer class, so when the change is observed, it makes the operations to this class.

We have understood so far, so let’s move on to the explanation of the codes, and how we use them.

I am using the ViewmodelProviders class to communicate with the view model in our View layer. This class allows us to access data and functions in our View model via view. I have shown its usefulness in the code example below.

LoginFragment.kt

lateinit var viewModel: LoginViewModel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

viewModel = ViewModelProviders.of(this)[LoginViewModel::class.java]
}

With the viewModel object, we can access the functions and live data in the LoginViewModel.

Model.kt

package com.example.fitnow.model

data class SignIn(val userEmail:String, val userPassword:String)

LoginViewModel.kt

class LoginViewModel : ViewModel() {

val loginErrorMessage = MutableLiveData<String>()
val loginInProgress = MutableLiveData<Boolean>()
val loginIsSuccess = MutableLiveData<Boolean>()

fun signInWithFirebase(userInformation:SignIn){
loginInProgress.value=true
FirebaseAuth.getInstance().signInWithEmailAndPassword(
userInformation.userEmail,
userInformation.userPassword)
.addOnCompleteListener {
if (it.isSuccessful){
loginIsSuccess.value=true
}else{
loginIsSuccess.value=false
loginErrorMessage.value=it.exception?.message.toString()
}
loginInProgress.value=false
}
}
}

As a result of the operations, we update the values ​​of LiveData and tell the observer what to do in the view. Available in 3 LiveData. We observe them in view.

LoginFragment.kt

lateinit var viewModel: LoginViewModel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

viewModel = ViewModelProviders.of(this)[LoginViewModel::class.java]
observeLiveData(view)
}

private fun observeLiveData(view:View) {
viewModel.loginIsSuccess.observe(viewLifecycleOwner, Observer { isSuccess->
isSuccess?.let {
if(it){
val action= LoginFragmentDirections.actionLoginFragmentToProfileFragment()
Navigation.findNavController(view).navigate(action)
}
}
})

viewModel.loginErrorMessage.observe(viewLifecycleOwner, Observer { error ->
error?.let {
Toast.makeText(context,error,Toast.LENGTH_LONG).show()
// Show what is wrong with Toast
}
})

viewModel.loginInProgress.observe(viewLifecycleOwner, Observer { loading ->
loading?.let {
if(it) //loading true
else //loading false
}
})
}

We observe the LiveData values ​​in the observeLiveData function. This is how we check the status of the values ​​and provide the necessary actions.

Summary

MVVM architecture has now become compulsory for advanced Android applications. In this article, I tried to give you information about what MVVM architecture is. However, the beginning part I’ve described is that we need to run more than one example to understand this structure.

Thanks so much for reading. See you again and be happy :=)

--

--