Andrey Danilov
Andrey Danilov

Reputation: 6602

How to inject dependency using koin in top level function

I have top-level function like

fun sendNotification(context:Context, data:Data) {
    ...//a lot of code here
}

That function creates notifications, sometimes notification can contain image, so I have to download it. I`m using Glide which is wrapped over interface ImageManager, so I have to inject it. I use Koin for DI and the problem is that I cannot write

val imageManager: ImageManager by inject()

somewhere in my code, because there is no something that implements KoinComponent interface.

The most obvious solution is to pass already injected somewhere else imageManager as parameter of function but I dont want to do it, because in most cases I dont need imageManager: it depends on type of Data parameter.

Upvotes: 19

Views: 8282

Answers (2)

w201
w201

Reputation: 2228

I did it in this way

fun Route.general() {

val repo: OperationRepo by lazy { GlobalContext.get().koin.get() }
...
}

Upvotes: 5

Andrey Danilov
Andrey Danilov

Reputation: 6602

Easiest way is to create KoinComponent object as wrapper and then to get variable from it:

val imageManager = object:KoinComponent {val im: ImageManager by inject()}.im

Btw its better to wrap it by some function, for example I use

inline fun <reified T> getKoinInstance(): T {
    return object : KoinComponent {
        val value: T by inject()
    }.value
}

So if I need instance I just write

val imageManager:ImageManager = getKoinInstance()

or

val imageManager = getKoinInstance<ImageManager>()

Upvotes: 46

Related Questions