All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.wulkanowy.sdk.hebe.ResettableLazyManager.kt Maven / Gradle / Ivy

Go to download

Unified way of retrieving data from the UONET+ register through mobile api and scraping api

There is a newer version: 2.7.0
Show newest version
package io.github.wulkanowy.sdk.hebe

import java.util.LinkedList
import kotlin.reflect.KProperty

/**
 * see https://stackoverflow.com/a/35757638/6695449
 */
internal class ResettableLazyManager {
    // we synchronize to make sure the timing of a reset() call and new inits do not collide
    val managedDelegates = LinkedList()

    fun register(managed: Resettable) {
        synchronized(managedDelegates) {
            managedDelegates.add(managed)
        }
    }

    fun reset() {
        synchronized(managedDelegates) {
            managedDelegates.forEach { it.reset() }
            managedDelegates.clear()
        }
    }
}

internal interface Resettable {
    fun reset()
}

internal class ResettableLazy(val manager: ResettableLazyManager, val init: () -> PROPTYPE) : Resettable {
    @Volatile
    var lazyHolder = makeInitBlock()

    operator fun getValue(thisRef: Any?, property: KProperty<*>): PROPTYPE {
        return lazyHolder.value
    }

    override fun reset() {
        lazyHolder = makeInitBlock()
    }

    fun makeInitBlock(): Lazy {
        return lazy {
            manager.register(this)
            init()
        }
    }
}

internal fun  resettableLazy(manager: ResettableLazyManager, init: () -> PROPTYPE): ResettableLazy {
    return ResettableLazy(manager, init)
}

internal fun resettableManager(): ResettableLazyManager = ResettableLazyManager()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy