2

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.

advice
  • 5,778
  • 10
  • 33
  • 60

1 Answers1

3

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

    ...
}
Demigod
  • 5,073
  • 3
  • 31
  • 49
  • For your first suggestion, since `Device` is a `data class` I'm trying to keep it very simple and don't want to pass a `MyStorage` object to it. Do you have any other ideas on how to create it? – advice Feb 28 '19 at 19:26
  • I decided to add a `Builder` to `Device`. `factory { Device.Builder(get()).build() }`. That seems like it works, do you think that's a good idea? – advice Feb 28 '19 at 19:35
  • Well, `Builder` pattern seems to be a bit redundant solution here. I think it could be easily replaced with a factory method, for example. Or with a constructor. Choose what suits your need most :) – Demigod Mar 01 '19 at 08:57