Best practice for Android MVVM startActivity

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

    The answer to your question is what is your goal?

    If you want to use MVVM for separation of concerns so that you can unit test your Viewmodel then you should try to keep everything that requires a Context separate from your Viewmodel. The Viewmodel contains the core business logic of your app and should have no external dependencies.

    However I like where you are going :) If the decision which Activity is opened lies in the View, then it is very very hard to write a JUnit test for it. However you can pass an object into the Viewmodel which performs the startActivity() call. Now in your Unit test you can simply mock this object and verify that the correct Activity is opened

提交回复
热议问题