I am trying to inject singleton Media Player insta...
# dagger
k
I am trying to inject singleton Media Player instance to use in my 3 View Pager fragments. The injection seem works, I can use instance of Media Player in different fragments, but it is not singleton. The key thing is when I play music in a fragment, switch to another view pager fragment -> play music there -> it should stop the current music and play the one I choose.
Copy code
@Provides
    @Singleton
    fun provideMediaPlayer(): MediaPlayer {
        return MediaPlayer.create(applicationContext, R.raw.sample)
    }

//AppComponent
@Component(modules = [AppModule::class])
@Singleton
interface AppComponent {
    fun inject(activity: MainMusicActivity)

    fun inject(fragment: FeaturedFragment)

    fun inject(fragment: MyMusicFragment)
}
This is inject in fragment, I try both @Inject and @Inject set
Copy code
@Inject
    lateinit var mediaPlayer: MediaPlayer
My question is am I using dagger correctly? Or is there any better way for getting singleton instance of media player with these view pager fragments
j
Hey 👋 overall it looks good. You can make sure if you inject the same instance by debugging your code and see it its the same instance. Maybe the bug is somewhere else. What you can potentially do better is to use dagger library for android. it adds some useful functionality or new and shiny Hilt. https://dagger.dev/dev-guide/android.html
👍 1
a
@KayCee How do you invoke the
inject(fragment)
call?