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

ru.hnau.jutils.getter.MutableGetter.kt Maven / Gradle / Ivy

The newest version!
package ru.hnau.jutils.getter

import ru.hnau.jutils.TimeValue
import ru.hnau.jutils.getter.base.GetterSync
import ru.hnau.jutils.helpers.Outdatable
import ru.hnau.jutils.helpers.toOutdatable


open class MutableGetter(
        private val valueLifetime: TimeValue? = null,
        private val getter: (P) -> V
): GetterSync {

    companion object {

        fun  simple(
                valueLifetime: TimeValue? = null,
                getter: () -> V
        ) = MutableGetter(
                valueLifetime = valueLifetime,
                getter = { getter.invoke() }
        )

        fun  simple(
                value: V
        ) =
                MutableGetter.simple { value }

    }

    private var value: Outdatable? = null

    val existence: V?
        get() = value?.value

    fun clear() {
        value = null
    }

    fun setValue(value: V) {
        this.value = value.toOutdatable(valueLifetime)
    }

    override fun get(param: P): V = synchronized(this) {
        var value = existence
        if (value == null) {
            value = getter.invoke(param)
            setValue(value)
        }
        return@synchronized value
    }

}

fun  V.toMutableGetter() =
        MutableGetter.simple(this)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy