tech.codingzen.kdi.data_structure.Providers.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kdi Show documentation
Show all versions of kdi Show documentation
0 dependency kotlin dependency injection
package tech.codingzen.kdi.data_structure
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import tech.codingzen.kdi.Provider
/**
* Commonly used [Provider] construction is contained in this object
*/
object Providers {
/**
* Singleton Creator
*
* @param T component type
* @param [provider] creates an instance of type T
* @return Creator that only invokes [provider] a single time
*/
inline fun single(crossinline provider: Provider): Provider {
val mutex = Mutex()
var component: T? = null
return {
mutex.withLock {
if (component == null) {
val t = provider(this)
component = t
return@withLock t
}
else component!!
}
}
}
/**
* Instance Creator
*
* @param T component type
* @param [t] value of creation
* @return Creator that always returns [t]
*/
fun instance(t: T): Provider = { t }
}