-
-
Notifications
You must be signed in to change notification settings - Fork 690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to inject a fragment/activity? (circular dependency) #18
Comments
Hello @obaied your are here in a circular dependency situation. The best way to handle it by property or a function and not directly by constructor. Bind MainActivity <-> AudioPlayer in 2 times. I propose you something like: add the class AudioPlayer() {
lateinit var context: Activity
fun doToast() {
Toast.makeText(context, "Running Audio player...", Toast.LENGTH_SHORT).show()
}
} bind lately this class MainActivity : BaseActivity() {
override val contextName = "MainActivity"
val audioPlayer by inject<AudioPlayer>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout)
audioPlayer.context = this
audioPlayer.doToast()
}
} no need to inject context in constructor fun appModules() = listOf(applicationModule())
class applicationModule : AndroidModule() {
override fun context() = applicationContext {
context(name = "MainActivity") {
provide { AudioPlayer() }
}
} Other point: if you audio player just need a context, you can inject the |
Got it! Thanks @arnaudgiuliani. I was just trying to see if Koin can automatically inject custom Android components (like Dagger). Cheers! |
Nice 👍 |
Hey!
This is not your typical situation but please humour me :)
How can an activity/application/fragment be injected as a dependency?
Assuming I have a class
AudioPlayer
:Which I'll need to inject inside
MainActivity
:How would I provide
MainActivity
as a dependency forAudioPlayer
?Here is the app module class:
The text was updated successfully, but these errors were encountered: