I'm exploring the ViewModel from the Android Jetpack suite and I am not sure which of these two approaches is regarded as the most "right" to have some data that need Context to be obtained (for example reading a local JSON file in the /asset
folder) inside the ViewModel
- Have an external context-aware entity (Fragment/Activity/Application/Centralised function) inject the data to the ViewModel in the constructor (here done with the Koin library from the Application class)
class MyApp : Application() {
private val someListOfData by lazy {
// read some local json using the Context
}
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyApp)
modules(module {
viewModel { MyViewModel(someListOfData) }
})
}
}
}
class MyFragment : Fragment() {
// ViewModel injected with Koin
val viewModel: MyViewModel by viewModel()
// Fragment body
}
class MyViewModel(private val listOfData: List<String>) : ViewModel() {
// ViewModel body with data passed in the constructor
}
- Use a AndroidViewModel instead of a ViewModel and leverage its knowledge of the hosting Application to retrieve the data from inside the ViewModel
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyApp)
modules(module {
viewModel { MyViewModel(this@MyApp) }
})
}
}
}
class MyFragment : Fragment() {
// ViewModel injected with Koin
val viewModel: MyViewModel by viewModel()
// Fragment body
}
class MyViewModel(app: Application) : AndroidViewModel(app) {
private val someListOfData by lazy {
// use Context to obtain the data
}
}