so I am new in MVVM pattern in Android. I want to perform two actions, when a button is clicked then first I check the internet connection, if the internet connection is available then perform login to server.
here is my ViewModel
class LoginViewModel(application: Application) : AndroidViewModel(application) {
private val _hasInternetConnection = MutableLiveData(false)
val hasInternetConnection: LiveData<Boolean>
get() = _hasInternetConnection
fun checkIfItHasInternetConnection() {
if (InternetConnection.checkConnection(getApplication())) {
_hasInternetConnection.value = true
} else {
_hasInternetConnection.value = false
}
}
fun performLogin() {
}
}
and here is my fragment
class LoginFragment : Fragment() {
lateinit var model: LoginViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
model = ViewModelProvider(this).get(LoginViewModel::class.java)
button.setOnClickListener {
model.checkIfItHasInternetConnection()
}
model.hasInternetConnection.observe(this, Observer { hasInternetConnection ->
if (!hasInternetConnection) {
longToast("You have no internet connection")
} else {
}
})
}
}
The problem is, I am not sure where do I have to call performLogin
method from my viewmodel, do I have to call it in my fragment like this in the observer ?
model.hasInternetConnection.observe(this, Observer { hasInternetConnection ->
if (!hasInternetConnection) {
longToast("You have no internet connection")
} else {
model.performLogin()
}
})
or do I have to call it inside the viewmodel itself after perform internet connection checking ? like this
// inside viewModel
fun checkIfItHasInternetConnection() {
if (InternetConnection.checkConnection(getApplication())) {
_hasInternetConnection.value = true
performLogin()
} else {
_hasInternetConnection.value = false
}
}
sorry if the question is too basic, I try to learn MVVM, and from the tutorials I watch, it seems I have to call the method in viewModel from the fragment, but it will be more convenient if I call it from the viewmodel itself. I need to know the correct way to solve case like this