简体   繁体   English

如何在对象类kotlin的Dagger中使用Application Context

[英]How to used Application Context in Dagger in object class kotlin

How to used Application Context in Dagger2 如何在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. 因此需要提供一个上下文,该如何在对象类中获取Dagger应用程序上下文。

Is this possible or there is another way to achieve?? 这可能还是有另一种方式实现?

Instead of object SocketConnection { 代替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时,无需使用Kotlin object关键字等效于静态单例。 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. 与通过Kotlin object关键字手动声明单例相比,Dagger 2具有更灵活的范围管理,并且您在AppModule提供的所有依赖AppModule都将有效地最终成为应用程序作用域的单例。

If your SocketConnection is intended to be a singleton, make it a class provided in your AppModule or another module with @Singleton scope: 如果您SocketConnection旨在成为一个单身,使它成为一个class你提供AppModule或与其他模块@Singleton范围:

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 : @Inject注释构造函数,或者如果您想在AppModule提供它,则注释它:

@Module
class AppModule(private val app: App) {

    @Provides
    @Singleton
    fun provideSocketConnection(app: App): SocketConnection =
        SocketConection(app)

}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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