{
private var instance: T? = null
fun getInstance() = instance ?: builder().also { instance = it }
fun destroy(){
instance = null
}
}
Ну и пропертя:
private var mainComponent = Component<MainComponent>({ getAppComponent().mainComponentBuilder().build() })
Норм?
Можно реализовать свой Lazy: class ResettableLazy<out T>(private val initializer: () -> T) : Lazy<T> { @Volatile private var t: T? = null override val value: T get() { val t1 = t if (t1 !== null) { return t1 } return synchronized(this) { val t2 = t if (t2 !== null) { t2 } else { val t3 = initializer() t = t3 t3 } } } override fun isInitialized(): Boolean = t !== null fun reset() = synchronized(this) { t = null } } typealias MainComponent = Int val mainComponentLazy = ResettableLazy(::initMainComponent) val mainComponent: MainComponent by mainComponentLazy private var i = 0 fun initMainComponent() = i++ fun main(args: Array<String>) { println(mainComponent) println(mainComponent) mainComponentLazy.reset() println(mainComponent) println(mainComponent) mainComponentLazy.reset() println(mainComponentLazy.value) println(mainComponentLazy.value) mainComponentLazy.reset() println(mainComponentLazy.value) println(mainComponentLazy.value) }
Обсуждают сегодня