从一个dagger2模块提供SharedPreferences,在另一个dagger2模块中想要使用它,
怎么做?
以下代码似乎无效。
/ **组件* /
@Singleton
@Component(modules = arrayOf(DataManagerModule::class,
AnotherModule::class))
interface DataManagerComponent {
fun getDataManager() : DataManager
fun getSharedPreferences() : SharedPreferences
}
/ **模块1 * /
@Module
class DataManagerModule(@ApplicationContext private val appContext: Context) {
@Singleton
@Provides
@ApplicationContext
fun provideApplicationContext(): Context = appContext
@Singleton
@Provides
fun provideSharedPreferences(): SharedPreferences {
return appContext.getSharedPreferences(appContext.packageName,
Context.MODE_PRIVATE)
}
}
/ **模块2 * /
@Module
class AnotherModule(private val config1: String?, private val config2: Int?) {
@Provides
@Singleton
internal fun provideClass2(context: Context): Class2 {
if (config2 == null) {
// how to get the preferences???
// getSharedPreferences().edit().getInt(Constants.Settings, -1)
}
return class2(config1, config2, context)
}
}
答案 0 :(得分:1)
由于所有这些工件共享相同的范围,并且组件是使用两个模块构建的,因此您应该只需将SharedPreferences
作为参数添加到provideClass2()
,以便在构造中使用它Class2
,如此:
@Provides
@Singleton
internal fun provideClass2(context: Context, prefs: SharedPreferences): Class2 {
...
}
答案 1 :(得分:1)
由于您已经定义了如何从DataManagerModule类中检索SharedPreferences,您只需更改
internal fun provideClass2(context: Context): Class2 {
...
}
到
internal fun provideClass2(sharedPreferences: SharedPreferences): Class2 {
...
}
让另一个类扩展Application类并将其声明为AndroidManifest,如下所示:
class App: Application() {
lateinit var dataManagerComponent: DataManagerComponent
override fun onCreate() {
super.onCreate()
dataManagerComponent = DaggerDataManagerComponent.builder()
.dataManagerModule(DataManagerModule(this))
.anotherModule(AnotherModule("config1", 123))
.build()
}
}
修改您的组件以包含注入功能
@Singleton
@Component(modules = arrayOf(DataManagerModule::class,
AnotherModule::class))
interface DataManagerComponent {
fun getDataManager() : DataManager
fun getSharedPreferences() : SharedPreferences
// The activity/fragment you will need the values
fun inject(target: MainActivity)
}
然后将其注入活动
class MainActivity : AppCompatActivity() {
@Inject lateinit var class2: Class2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as App).dataManagerComponent.inject(this)
Log.i("CLASS2", class2.toString())
}
}