commonMain.com.ivianuu.injekt.common.Scope.kt Maven / Gradle / Ivy
/*
* Copyright 2022 Manuel Wrage. Use of this source code is governed by the Apache 2.0 license.
*/
package com.ivianuu.injekt.common
import com.ivianuu.injekt.Inject
import com.ivianuu.injekt.Provide
import com.ivianuu.injekt.Spread
import com.ivianuu.injekt.Tag
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
class Scope : SynchronizedObject() {
@PublishedApi internal val values = hashMapOf()
inline operator fun invoke(key: Any, init: () -> T): T = synchronized(this) {
val value = values.getOrPut(key) { init() ?: NULL }
(if (value !== NULL) value else null) as T
}
inline operator fun invoke(@Inject key: TypeKey, init: () -> T): T =
invoke(key.value, init)
companion object {
@PublishedApi internal val NULL = Any()
}
}
@Tag annotation class Scoped {
@Provide companion object {
@Provide inline fun <@Spread T : @Scoped S, S : Any, N> scoped(
scope: Scope,
key: TypeKey,
crossinline init: () -> T,
): S = scope(key) { init() }
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy