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

tech.codingzen.kdi.data_structure.Providers.kt Maven / Gradle / Ivy

There is a newer version: 2.1.0
Show newest version
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 }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy