简体   繁体   中英

How to used Application Context in Dagger in object class kotlin

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??

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()
        })
     }
}

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)

}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM