What's the most common or recommended approach to access an application's context in a data source class of a MVVM setup using Jetpack Compose?
Specifically, I have the following setup:
class MainActivity : ComponentActivity()
class MyViewModel(private val _myRepository: MyRepository) : ViewModel()
class MyRepository(private val _localDataSource = MyFileSource())
.class MyFileSource()
I want to access local files.However, methods such as getFilesDir() require a context.
LocalContext.current
can only be used in the context of a @Composable function, thus inside the view.
Should this context be passed down the chain via view -> view model -> repository -> data source? It feels (to me) like there might be a more elegant way.
Yes, you are right that the context would need to be passed down, since the ui is on top and the context originates there.
A more elegant way, however, is to bypass providing the context yourself and let a dependency injection framework like Hilt handle this for you. When you have set it up (adding dependencies to your gradle files and adding some annoations to you application, activity and viewmodel), you can simply declare your class like this:
class MyFileSource @Inject constructor(
@ApplicationContext applicationContext: Context,
)
Since you would never explicitly instantiate this class (or any other classes in between, like the repository or the viewmodel), there'll never be a need to provide the context object yourself.