Best practice for Android MVVM startActivity

前端 未结 6 1247
你的背包
你的背包 2021-01-30 13:16

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

6条回答
  •  粉色の甜心
    2021-01-30 13:36

    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
            }
    
    1. 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:

    
    
     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

提交回复
热议问题