Just a general question about MVVM: Where to put c...
# android
a
Just a general question about MVVM: Where to put code for IO Operations? I know you shouldn’t put business logic in the UI layer but also no context in the VIewModel. So where to put for example a function to download a file to internal storage? I need the context for that and it also has nothing to do with UI.
😶 1
i
In repository. You launch bg operation from vm and in the bg your repository works with files, network etc
a
But how do I get the context in my repository?
From my UI layer (Button click) I call the viewModel which calls the repository and there I write the Code to save the file? So I still have to pass the context all the way through the viewmodel?
i
usually you would inject context in repository. or better contentResolver
l
Create function VM fun (pass prams context) -> call from UI layer( in this have context)
r
I've found Hilt to work really nicely for this. If you annotate your VM with
@HiltViewModel
you can inject any class that talks to a DB or does networking in a really convenient way (using
@Inject
) and then from your VM you can launch a coroutine that is scoped to your VM's lifecycle using
viewModelScope.launch {
and then call back to your UI with a
LiveData
. (https://developer.android.com/training/dependency-injection/hilt-android)
Context in any Hilt object is obtained with
@ApplicationContext
p
If you have an Application object, you could use that as well