问题
I'm using the Koin library for an Android project. I want to share some instances between modules since they are used a lot throughout the application. For instance:
val moduleA = module {
scope(named<FragmentA>()) {
scoped { FirebaseFirestore.getInstance() }
scoped { LocalDatabase.getInstance(App.sContext) }
scoped { NetworkDataSourceA(get()) }
}
}
val moduleB = module {
scope(named<FragmentB>()) {
scoped { FirebaseFirestore.getInstance() }
scoped { LocalDatabase.getInstance(App.sContext) }
scoped { NetworkDataSourceB(get()) }
}
}
As we can see from the following modules the FirebaseFirestore.getInstance()
and the LocalDatabase.getInstance(App.sContext)
are the same between both modules.
Is there a way where I can declare lets say a moduleC
that contains FirebaseFirestore.getInstance()
and the LocalDatabase.getInstance(App.sContext)
and then call it on the moduleA
and moduleB
?
回答1:
You can do this by creating scope. Though I didn't tried.
val moduleA = module { scope(named("CommonScope")) { scoped { FirebaseFirestore.getInstance() } scoped { LocalDatabase.getInstance(App.sContext) } scoped { NetworkDataSourceA(get()) } scoped { NetworkDataSourceB(get()) } } }
Now, create your scope in your FragmentA using below line.( also same for FragmentB for NetworkDataSourceB)
private val commonScope = getKoin().getOrCreateScope("scope1",named("CommonScope")) val networkDataSourceA = commonScope.get<NetworkDataSourceA>()
And In
onDestroy
methodcommonScope.close()
For more detail check koin documentation (8th point)
来源:https://stackoverflow.com/questions/56721048/koin-sharing-instances-between-modules