Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject dependency using koin in top level function

Tags:

kotlin

koin

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.

like image 892
Andrey Danilov Avatar asked Jun 13 '18 14:06

Andrey Danilov


1 Answers

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>()
like image 191
Andrey Danilov Avatar answered Dec 01 '22 19:12

Andrey Danilov