Should I use view model to start other activities ...
# android
i
Should I use view model to start other activities and/or show toast messages by sending context to view model through methods: from activity -> myVm.someMethod(applicationContext), from view model -> someMethod(applicationContext) { startActivity(Intent(applicationContext...))}
google 1
a
Ideally no, you should separate the Android framework and not expose it to your viewmodels, but sometimes you need it. In that case you can use AndroidViewModel, that is only a ViewModel with a reference to your app context (Not the Activity/Fragment one).
👍 1
j
You don’t necessarily have to separate them. By doing you often end up with more abstraction/more code. I typically do for the sake of ease of testing but you can use instrumented tests and robolectric if you couple Android and business logic
b
NO!
⚠️ Never put an activity context inside a viewmodel. a toast is an element of the view and should be paced in it. You can use a singleEvent like
showMessage
and show a toast in the regarding view. There are only rare situations, where you can use a context in the viewmodel eg. for android libraries or persistence. It is recommended to use the
applicationContext
instead to prevent leaks. https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel.html
👍🏽 3
👍 4