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<Boolean?>()
3.create method for this private field:
val showSignIn: LiveData<Boolean?>
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<Boolean?>()
val showSignIn: LiveData<Boolean?>
get() = _showSignIn
fun callSignIn() {
_showSignIn.value = true
}
- Call the method in your activity or fragment :
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:
<variable
name="eventViewModel"
type=packageName.Event" />
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