Reputation: 685
I'm trying to write a game on Android with dagger 2 features. I have a problem with @Singleton.
I have created the module:
@Module
class SharedModule {
@Singleton
@Provides
fun getDeviceService(): DeviceService = DeviceService()
@Provides
@Singleton
fun getAssetsService(): AssetsService = AssetsService()
@Singleton
@Provides
fun getGameService(): GameService = GameService()
}
and the component
@Singleton
@Component(modules = [SharedModule::class])
interface SharedComponent {
fun inject(app: MazeSlayers)
fun inject(screen: SplashScreen)
}
but when I try to inject objects I got always a new instance of it, app class:
class MazeSlayers : Game() {
@Inject
lateinit var assetsService: AssetsService
@Inject
lateinit var gameService: GameService
override fun create() {
DaggerSharedComponent.create().inject(this)
gameService.game = this
assetsService.add(Asset.LOGO)
this.setScreen(SplashScreen())
}
override fun render() {
super.render()
}
}
and SplashScreen
class SplashScreen : ScreenAdapter() {
lateinit var batch: SpriteBatch
var img: Texture? = null
@Inject
lateinit var deviceService: DeviceService
@Inject
lateinit var assetsService: AssetsService
@Inject
lateinit var gameService: GameService
override fun show() {
DaggerSharedComponent.create().inject(this)
batch = gameService.batch
img = assetsService.getTexture(Asset.LOGO)
}
...
What I do wrong?
[SOLUTION]
One shared kotlin object resolved my issue
object DI {
val shared: SharedComponent = DaggerSharedComponent.create()
}
Upvotes: 0
Views: 131
Reputation: 1452
You're creating your component twice. Hence each component will independently create its objects. @Singleton's effect is that if you ask the same component for the same binding twice you get the same object.
The solution is to somehow create your component only once and let it create all the objects you need. I have no idea what's the way to achieve that in LibGDX.
Upvotes: 1