1.2.0
Released a new version 1.2.0
.
We can inject dependencies using Dagger instead of using @InjectPreference
annotation.
Here is the way to migrate Dagger.
1. If you using PreferenceEntity
without PreferenceComponent
.
@Provides
@Singleton
fun provideInitialEntity(context: Context): Preference_InitialEntity {
return Preference_InitialEntity.getInstance(context)
}
@Provides
@Singleton
fun provideSettingEntity(context: Context): Preference_SettingEntity {
return Preference_SettingEntity.getInstance(context)
}
1. If you using PreferenceEntity
with PreferenceComponent
.
1. Add method for injecting an instance of PreferenceComponent
to Dagger's Builder
.
@Singleton
@Component( ... )
interface AppComponent : AndroidInjector<DaggerApplication> {
@Component.Builder
interface Builder {
@BindsInstance fun application(application: Application): Builder
+ @BindsInstance fun preferenceRoom(prefAppComponent: PrefAppComponent): Builder
fun build(): AppComponent
}
}
2. Inject an initialized PreferenceComponent
that generated by the compiler.
The most important thing is the appComponent
should be initialized lazily or in the onCreate
.
Because the Context
is null
when initializing properties in the Application
class.
class MyApplication: DaggerApplication() {
private val appComponent by lazy {
DaggerAppComponent.builder()
.application(this)
+ .preferenceRoom(PreferenceComponent_PrefAppComponent.init(this))
.build()
}
}
3. Make entity providing abstract methods in the PreferenceComponent
@PreferenceComponent(entities = [InitialEntity::class, SettingEntity::class])
interface PrefAppComponent {
// provides entities
fun initialEntity(): InitialEntity
fun settingEntity(): SettingEntity
4. Provide instances of the instances on the module.
I just created a new module: PreferenceModule
.
@Module
class PreferenceModule {
@Provides
@Singleton
fun provideInitialEntity(prefAppComponent: PrefAppComponent): Preference_InitialEntity {
return prefAppComponent.initialEntity() as Preference_InitialEntity
}
@Provides
@Singleton
fun provideSettingEntity(prefAppComponent: PrefAppComponent): Preference_SettingEntity {
return prefAppComponent.settingEntity() as Preference_SettingEntity
}
}
5. It's finished. And you can inject dependency using @Inject
annotation by dagger.
class SnsViewModel @Inject constructor(
val initialEntity: Preference_InitialEntity,
val settingEntity: Preference_SettingEntity
) : ViewModel() {