https://kotlinlang.org logo
#android
Title
# android
i

Ive Vasiljevic

03/05/2019, 9:52 AM
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

Alhima

03/05/2019, 10:35 AM
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

Jiddles

03/05/2019, 11:24 AM
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

Bino

03/05/2019, 11:29 AM
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
2 Views