简体   繁体   中英

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.

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

    ...
}

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