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.

推荐答案

最简单的方法是创建KoinComponent个对象作为包装器,然后从中获取变量:

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

Btw its better to wrap it by some function, f或 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()

val imageManager = getKoinInstance<ImageManager>()

Kotlin相关问答推荐

为什么Kotlin协程程序即使有延迟也能输出?

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

处理合成层次 struct 中的深层按钮以切换视图

访问者闭包中的Kotlin序列yield 率

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

按钮无法在 Android Studio 上打开新活动

Kotlin 列表扩展功能

Kotlin spring boot @RequestBody 验证未触发

Kotlin 使用迭代索引过滤 lambda 数组

Kotlin - 当表达式返回函数类型

为什么 Dialog 没有 NavController [Missing]?

Jetpack Compose – LazyColumn 不重组

kotlin RecyclerView分页

空对象引用上的 TransitionSet ArrayList.size()

(kotlin的Moshi)@Json vs@field:Json

如何在Android Studio 4.1中默认启用Kotlin Android扩展

类型不匹配推断类型为单位,但应为空

有没有办法在Kotlin中设置一个私有常量

在 intelliJ 元素中集成 Kotlinx 协程

Kotlin:如何使用扩展函数扩展枚举类