commonMain.org.kodein.di.properties.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kodein-di-js Show documentation
Show all versions of kodein-di-js Show documentation
KODEIN Dependency Injection Core
package org.kodein.di
import org.kodein.type.TypeToken
import org.kodein.type.erasedOf
import kotlin.reflect.KProperty
/**
* A trigger is used to force retrieval at a given time rather than at first property access.
*
* 1. Set a trigger to [DIAware.diTrigger].
* 2. When you want retrieval to happen, call [trigger].
*/
@Suppress("unused")
public class DITrigger {
/**
* All properties that will be retrieved when the trigger happens.
*/
public val properties: MutableList> = ArrayList()
/**
* Trigger retrieval of all properties that are registered in [properties].
*/
public fun trigger(): Unit = properties.forEach { it.value }
}
public interface LazyDelegate {
/** @suppress */
public operator fun provideDelegate(receiver: Any?, prop: KProperty): Lazy
}
/**
* A property delegate provider for DI retrieval.
* Provides a `Lazy` value that, when accessed, retrieve the value from DI.
*
* In essence, the DI object is accessed only upon retrieving.
*/
public class DIProperty(internal val trigger: DITrigger?, public val originalContext: DIContext<*>, private val get: (DIContext<*>, String) -> V) : LazyDelegate {
override fun provideDelegate(receiver: Any?, prop: KProperty): Lazy = lazy {
@Suppress("UNCHECKED_CAST")
val context = if (receiver != null && originalContext === AnyDIContext) DIContext(erasedOf(receiver) as TypeToken, receiver) else originalContext
get(context, prop.name) } .also { trigger?.properties?.add(it)
}
}
public class DIPropertyMap(private val base: DIProperty, private val map: (I) -> O) : LazyDelegate {
override fun provideDelegate(receiver: Any?, prop: KProperty): Lazy = lazy { map(base.provideDelegate(receiver, prop).value) }.also { base.trigger?.properties?.add(it) }
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy