SinghDeveloper
1 min readJul 6, 2021

--

MVVM Works and Why Not destroying on configuration change

Mvvm is a powerful library to handle views or data in activity and fragment to handle configuration changes but search on lots sites articles and much more but there was not any good idea in clear words.

Some of the interviewers also asked the same question about how its works.

So now it's time to show some clear results.

class LoginViewModel(
private val mApplication: Application,
private val iRepository: ApiRepository,

) : BaseViewModel(mApplication){


private val _login: MutableLiveData<Resource<LoginModel.Data>> = MutableLiveData()
val loginResponse: LiveData<Resource<LoginModel.Data>>
get() = _login



fun clearData(){
_login.value =
Resource.Error("data")
}

fun sendLoginDeatils(userNumber: String, userLocation: String) =
viewModelScope.launch {
iRepository.sendLoginDetails(name = userNumber, lat_long = userLocation)
.onStart {
_login.value = Resource.Loading()
}
.catch { e->
_login.value =
Resource.Error(e.message ?: mApplication.somethingWentWrong())
}.collect {

if (it.status.equals("success") && it.message.equals("OTP Send")) {
_login.value = Resource.Success(it.data)
} else {
_login.value = Resource.Error(
it.message ?: mApplication.somethingWentWrong()
)
}

}

}


}

This is a sample view model class for the login screen.

Mvvm does not destroy on configure changes because they internally check to configure conditions activity change or rotate.

--

--