Dave Scheck
02/14/2023, 9:29 PMAssisted Injection
to pass runtime parameters into objects being injected. What I haven't been able to figure out is how to use that (or another mechanism) to choose the type of object being injected based on a runtime parameter. For example, without using DI I might do something like this
class RepoDataSourceScreenViewModel: ViewModel() {
var isSimulated = lookupIsSimulated()
val repository = ComponentRepository(isSimulated)
// This would be backed by a DB/sharedPref lookup
private fun lookupIsSimulated(): Boolean = false
}
class ComponentRepository(val isSimulated: Boolean) {
val dataSource = if(isSimulated) RealComponentDataSource() else SimComponentDataSource()
}
abstract class ComponentDataSource()
class RealComponentDataSource() {}
class SimComponentDataSource() {}
Is there an equivalent be in a Dagger/Hilt environment?jw
02/14/2023, 9:36 PMProvider<T>
argumentsDave Scheck
02/15/2023, 4:00 PM@Module
@InstallIn(SingletonComponent::class)
class ConfigModule {
@Provides
@Singleton
fun provideSimulationConfig(): SimulationConfig {
return SimulationConfig(false)
}
}
@Module
@InstallIn(ActivityRetainedComponent::class)
class RepoModule {
@Provides
fun provideComponentRepository(dataSource: ComponentDataSource): ComponentRepository {
return ComponentRepository(dataSource)
}
@Provides
fun provideDataSource(simulationConfig: SimulationConfig): ComponentDataSource {
return if (simulationConfig.isEnabled) {
SimComponentDataSource()
} else {
RealComponentDataSource()
}
}
}
Dave Scheck
02/15/2023, 4:02 PMjw
02/15/2023, 5:43 PM