Search code examples
androidkotlinkoin

Koin Kotlin - How to use inject/get outside of Activity


I'm currently trying to implement Koin into my Android app. It works well within Activities where I can access get() or inject(), but outside of those Classes I'm unable to use them.

For example, I have a very simple class called Device that will just create an Object of the user's device. I need to get a reference to MyStorage within there.

data class Device(
    val username: String,
    ...
) {

    companion object {

        fun get(): Device {
            val storage: MyStorage = get() // does not work

            val username = storage.username

            return Device(
                username,
                ...
            )
        }
    }
}

But get() does not work within this class, and manually adding the import doesn't help.

I also saw this answer, https://stackoverflow.com/a/49629378/3106174, which has extending KoinComponent, but that doesn't work in this case or others I've run into such as top-level functions outside any class.

Any tips would be greatly appreciated. Thanks.


Solution

  • Well, I would consider making Device object through dependency injection also, where it could accept MyStorage injected in a constructor.

    val appModule = module {
    
        factory { Device(get()) }    // MyStorage injected using get()
    
    }
    

    But if it doesn't suit your need, try getting MyStorage from ComponentCallbacks object (for example from the Application).

    class App : Application() {
    
        companion object {
            private lateinit var instance: App
    
            fun get(): App = instance
        }
    
        override fun onCreate() {
            super.onCreate()
            instance = this
        }
    
        fun getMyStorage(): MyStorage {
            return get()
        }
    }
    
    fun get(): Device {
        val storage: MyStorage = App.get().getMyStorage()
    
        ...
    }