I am building an Android App using MVVM and DataBinding. And I have a function inside my ViewModel that starts an Activity. Is it okay to have an onClick call inside a ViewModel
in MVVM we can use LiveData
for this Event . because ViewModel is Alive when the activity/Fragment
destroyed! So the best way is LiveData
1.Create Class Call Event
and Extends
It from ViewModel
:
class Event : ViewModel() {
2.create field from LiveData :
private val _showSignIn = MutableLiveData()
3.create method for this private field:
val showSignIn: LiveData
get() = _showSignIn
4.create method that you can setValue on your liveData:
fun callSignIn() {
_showSignIn.value = true
}
The final Event Class :
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class Event : ViewModel() {
private val _showSignIn = MutableLiveData()
val showSignIn: LiveData
get() = _showSignIn
fun callSignIn() {
_showSignIn.value = true
}
THe instance from eventViewModel :
private val eventViewModel = Event()
call the observe :
eventViewModel.showSignIn.observe(this, Observer {
startActivity(Intent(this, MainActivity::class.java))
})
and if you use the data binding
you can call callSignIn()
in onClick
XML :
in Variable tag:
android:onClick="@{() -> eventViewModel.callSignIn()}"
NOTE: do not forget set binding in your activity/fragment
:
binding.eventViewModel = eventViewModel
I search for the best way and Find it. I hope to help someone