'Best MVVM handling for functions that require context or activity?
So I have a fragment and a viewModel and I'm trying to keep it clean as much as possible. What is the best way to handle functions that require context and coroutine like data store? Or should it stay in the fragment class?
class LanguageFragment: Fragment() {
private val viewModel: LanguageViewModel by viewModels()
private val userDataStore = UserDataStore
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
subscribeForUI()
}
fun subscribeUI(){
viewModel.actionRequest.observe(viewLifecycleOwner) { action ->
when (action) {
LanguageViewModel.LanguageActions.Save ->{
lifecycleScope.launch {
userDataStore.saveStringData(
requireContext(),
DataStoreKeys.SELECTED_LANGUAGE,
selectedLanguage
)
(requireActivity() as MainActivity).setLanguage(selectedLanguage)
recreate(requireActivity())
}
}
}
}
ViewModel:
class LanguageViewModel: ViewModel() {
private val _actionRequest = SingleLiveEvent<LanguageActions>()
val actionRequest: LiveData<LanguageActions> = _actionRequest
fun saveAction() = _actionRequest.setValue(LanguageActions.Save)
sealed class LanguageActions{
object Save: LanguageActions()
}
}
Solution 1:[1]
If you ever find a situation where you need a context inside viewModel (situations like this needs to be avoided as much as possible), use AndroidViewModel.
https://developer.android.com/reference/androidx/lifecycle/AndroidViewModel
You'll have Application reference, where you can get context.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Filipe Oliveira |
