Search code examples
androidmvvmandroid-jetpack-compose

Access local files on Android in a data source via Jetpack Compose and MVVM


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:

  • A view via class MainActivity : ComponentActivity()
  • A view model via class MyViewModel(private val _myRepository: MyRepository) : ViewModel()
  • The repository is a mere class MyRepository(private val _localDataSource = MyFileSource()).
  • In 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.


Solution

  • 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.