Reputation: 51
How to used Application Context in Dagger2
@Module
class AppModule(private val app: App) {
@Provides
@Singleton
@AppContextQualifier
fun provideApplication(): App = app
}
in class like
object SocketConnection {
private fun listenSocketEvents() {
socket?.on(SocketContent.JOINED, { args ->
//Toast.makeText(context!!,"logout",Toast.LENGTH_LONG).show()
})
}
}
I want to toast when socket listens to any data. so need to provide a context how to get dagger application context in an object class.
Is this possible or there is another way to achieve??
Upvotes: 0
Views: 824
Reputation: 81529
Instead of object SocketConnection {
should be
@Singleton
class SocketConnection @Inject constructor(
@AppContextQualifier private val app: App
) {
private fun listenSocketEvents() {
socket?.on(SocketContent.JOINED, { args ->
Toast.makeText(app,"logout",Toast.LENGTH_LONG).show()
})
}
}
Upvotes: 1
Reputation: 21407
Using the Kotlin object
keyword to make an equivalent of a static singleton when you are using Dagger 2 is not necessary. Dagger 2 has a more flexible management of scopes than manually declaring singletons through the Kotlin object
keyword and all the dependencies you provide in your AppModule
will effectively end up as app-scoped singletons.
If your SocketConnection
is intended to be a singleton, make it a class
provided in your AppModule
or another module with @Singleton
scope:
class SocketConnection constructor(private val app: App) {
private fun listenSocketEvents() {
//
}
}
Annotate the constructor with @Inject
or alternatively if you want to provide it in your AppModule
:
@Module
class AppModule(private val app: App) {
@Provides
@Singleton
fun provideSocketConnection(app: App): SocketConnection =
SocketConection(app)
}
Upvotes: 0