Best practice for Android MVVM startActivity

前端 未结 6 1298
你的背包
你的背包 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:40

    The way I do it is, in your ViewModel:

    val activityToStart = MutableLiveData, Bundle?>>()
    

    This allows you to check the class of Activity started, and the data passed in the Bundle. Then, in your Activity, you can add this code:

    viewModel.activityToStart.observe(this, Observer { value ->
        val intent = Intent(this, value.first.java)
        if(value.second != null)
            intent.putExtras(value.second)
        startActivity(intent)
    })
    

提交回复
热议问题